Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular routing multiple paths to same component

Tags:

angular

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
    }
    ]
}
like image 633
Rachid O Avatar asked Sep 22 '17 12:09

Rachid O


2 Answers

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

like image 146
CornelC Avatar answered Sep 19 '22 14:09

CornelC


You can use a mapped array:

children: [
  // excluding the other paths for brevity
  ...['today', 'tomorrow', 'expired'].map(path => ({
    path,
    component: AccessRequestsComponent
  }))
]
like image 35
Bogdan D Avatar answered Sep 16 '22 14:09

Bogdan D