How to match route only if param is integer in Angular2?

后端 未结 1 850
孤独总比滥情好
孤独总比滥情好 2021-02-06 04:52

For example this router

{
    path: \'/client\',
    component: ClientRootComponent,
    children: [
        {path: \'\', component: ClientListComponent},
               


        
相关标签:
1条回答
  • 2021-02-06 05:09

    You can pass a custom matcher to your route

    import { defaultUrlMatcher } from '@angular/router/src/shared';
    
    function digitsMatcher(segments: UrlSegment[], segmentGroup: UrlSegmentGroup, route: Route): UrlMatchResult | null {
      const result = defaultUrlMatcher(segments, segmentGroup, route);
    
      if (!result || !result.consumed || result.consumed.length < 1) {
        return;
      }
    
      const re = /^\d+$/;
      const match = re.exec(result.consumed[0].path);
    
      if (match) {
        return result;
      }
    
      return null;
    }
    
    {
        path: '/client',
        component: ClientRootComponent,
        children: [
            {path: '', component: ClientListComponent},
            {path: ':clientId', component: ClientOpenComponent, resolve: makeResolver(ClientOpenResolver), matcher: digitsMatcher}
        ]
    },
    {
        path: '**',
        component: NotFoundComponent
    }
    

    The code is not tested

    See also

    • https://github.com/angular/angular/blob/73407351e7fa75250be8bdb6c1eb4f7d37f6f947/modules/%40angular/router/src/shared.ts#L39
    • https://angular.io/docs/ts/latest/api/router/index/Routes-type-alias.html
    • https://angular.io/docs/ts/latest/api/router/UrlMatcher
    0 讨论(0)
提交回复
热议问题