Angular URL Matcher

Если имеется несколько маршрутов для одного компонента:

const routes = [
    {
      path: '',
      redirectTo: 'today',
      pathMatch: 'full'
    },
    {
      path: 'today',
      component: SomeComponent
    },
    {
      path: 'tomorrow',
      component: SomeComponent
    },
    {
      path: 'expired',
      component: SomeComponent
    }
];

Или маршруты с опциональными параметрами

const routes = [
  { 
    path: '/UserComponent/:id', 
    component: UserComponent 
  },
  { 
    path: '/UserComponent', 
    component: UserComponent 
  },
];

То такую или более сложную логику можно объединить используя UrlMatcher:

function matcherFunction(url: UrlSegment[]) {
    if (url.length == 1) {
        const path = url[0].path;
         if(path.startsWith('today') 
           || path.startsWith('tomorrow') 
           || path.startsWith('expired')){
          return {consumed: url};
        }
    }
    return null;
}

const routes = [
    {
      path: '',
      redirectTo: 'today',
      pathMatch: 'full'
    },
    {
      matcher: matcherFunction,
      component: SomeComponent
    }
]

Официальный пример:

function htmlFiles(url: UrlSegment[]) {
  return url.length === 1 && url[0].path.endsWith('.html') ? ({consumed: url}) : null;
}

const routes = [{ matcher: htmlFiles, component: AnyComponent }];

Похожие записи

RxJS Pipeable Operators

Начиная с версии rxjs 5.5 операторы вместо цепочки вызовов применяются как параметры функции pipe.

Angular. Отличие baseHref от deployUrl

  • deployUrl - задаёт путь для статических (js, css) файлов в index.html.
  • baseHref - определяет base, используется в ссылках и маршрутизации (routing) Angular