Search code examples
javascriptangulartypescriptangular-route-segment

Angular 2 route to the same component with different urls


How can I route to the same component but with different urls and different data, for example

/exports/open  -  ExportsListComponent data: {exportstatus: 'open'}

/exports/submitted - ExportsListComponent data: {exportstatus: 'submitted'}

/exports/completed - ExportsListComponent data: {exportstatus: 'completed'}

this what I tried to do, also I have other routes that use ExportComponent but with similar route like exports/:exportId.

      { path: 'exports/jobs/:exportJobId', component: ExportComponent, canActivate: [RouteGuard], resolve: { exportJob: ExportJobResolver }, data: { allowed: ['inv', 'cr'] } },
      { path: 'exports/:exportId', component: ExportComponent, canActivate: [RouteGuard], resolve: { export: ExportResolver }, data: { allowed: ['inv', 'cr'] } },
      { path: 'exports', component: ExportsListComponent,
      children: [
        { path: 'open', component: ExportsListComponent ,  data: {exportstatus: 'open'}},
        { path: 'submitted', component: ExportsListComponent,  data: {exportstatus: 'submitted'} },
        { path: 'completed', component: ExportsListComponent, data: {exportstatus: 'completed'} }
      ],

The problem I have when I access url with /exports/open it routes to ExportComponent instead of ExportListComponent. How can I route with url to exports/open and route to ExportListComponent, instead of ExportComponent. The issue is when I route to /exports/open it would think 'open' is an id, but instead I need to route to ExportListComponent


Solution

  • According the official documentation:

    The order of the routes in the configuration matters and this is by design. The router uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes.

    So you have to move the exports/:exportId route entry bellow the exports entry.

    Like this

      { path: 'exports/jobs/:exportJobId', component: ExportComponent, canActivate: [RouteGuard], resolve: { exportJob: ExportJobResolver }, data: { allowed: ['inv', 'cr'] } },
      { path: 'exports', component: ExportsListComponent,
      children: [
        { path: 'open', component: ExportsListComponent ,  data: {exportstatus: 'open'}},
        { path: 'submitted', component: ExportsListComponent,  data: {exportstatus: 'submitted'} },
        { path: 'completed', component: ExportsListComponent, data: {exportstatus: 'completed'} }
      ],
      {path: 'exports/:exportId', component: ExportComponent, canActivate: [RouteGuard], resolve: { export: ExportResolver }, data: { allowed: ['inv', 'cr'] } },