Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable number of parameters in routes

I know we can set parameters in router paths using '/:id'. But I want to create an array of uncertain length like this: '/:id1/:id2/:id3/...'

Currently I'm managing up to three parameters like this:

const routes: Routes = [
    { path: '/:name1',  component: MyComponent,   canActivate: [ LocalUserGuard ] },
    { path: '/:name1/:name2',  component: MyComponent,   canActivate: [ LocalUserGuard ] },
    { path: '/:name1/:name2/:name3',  component: MyComponent,   canActivate: [ LocalUserGuard ] }

However I want to extend it to any number of parameters.

like image 247
Rohan Avatar asked Jun 25 '17 11:06

Rohan


Video Answer


1 Answers

If you want it to be completely arbitrary, you could use a wildcard route:

const routes: Routes = [
  { path: '**', component: MyComponent, canActivate: [ LocalUserGuard ] },
]

Then inside MyComponent you can access the URL segments via the ActivatedRoute:

@Component({...})
export class MyComponent { 
  constructor(private route: ActivatedRoute) {
    route.url.subscribe((segments: UrlSegment[]) => {
      // do whatever you need to with the segments
    });
  }
}

See example Plunker: http://plnkr.co/edit/9YYMwO?p=preview

like image 79
jonrsharpe Avatar answered Nov 16 '22 02:11

jonrsharpe