Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

angular routing multiple paths to same component

Is there a way to optimize this code from this

{
  path: 'access-requests',
  canActivate: [AccessGuard],
  component: AccessRequestsComponent,
  children: [
    {
      path: '',
      redirectTo: 'today',
      pathMatch: 'full'
    },
    {
      path: 'today',
      component: AccessRequestsComponent
    },
    {
      path: 'tomorrow',
      component: AccessRequestsComponent
    },
    {
      path: 'expired',
      component: AccessRequestsComponent
    }
    ]
}

to something like this

{
  path: 'access-requests',
  canActivate: [AccessGuard],
  component: AccessRequestsComponent,
  children: [
    {
      path: '',
      redirectTo: 'today',
      pathMatch: 'full'
    },
    {
      path: 'today | tomorrow | expired',
      component: AccessRequestsComponent
    }
    ]
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the UrlMatcher property.

    {
      path: 'access-requests',
      canActivate: [AccessGuard],
      component: AccessRequestsComponent,
      children: [
        {
          path: '',
          redirectTo: 'today',
          pathMatch: 'full'
        },
        {
          matcher: matcherFunction,
          component: AccessRequestsComponent
        }
        ]
    }

And

    export 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;
    }

Note: Untested code


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...