Djkobus
Djkobus

Reputation: 131

Dynamic angular router path

This is my current router:

const routes: Routes = [
  { path: '',  component: HomeComponent },
  { path: 'filter',  component: FiltersPageComponent},
  { path: 'filter/:continent',  component: FiltersPageComponent},
  { path: '**', canActivate: [RouteLoader], component: ErrorComponent},
];

I have a dynamic url that is created when a user searches for multiple destinations.

Example of url: localhost:4200/filter/africa/botswana/europe/spain/asia/china

Can I create 1 path that will accept this url without making multiple paths like below?

{ path: 'filter/:test/:test2/:test3/:test4/:test5/:test6',  component: FiltersPageComponent}

Upvotes: 2

Views: 9031

Answers (4)

Djkobus
Djkobus

Reputation: 131

The solution I ended up using was this:

{ path: 'filter',  component: FiltersPageComponent,
  children: [
    { path: '**', component: FiltersPageComponent}
  ]
},

The only problem I can think of when using this method is that the user can randomly put anything after filter/ in the url and it will still redirect to the filtersPageComponent.

Upvotes: 2

JeB
JeB

Reputation: 12133

With path params it is impossible (and also wrong), but you should be able to do this with query params like this:

localhost:4200/yourroute?filter=africa&filter=botswana&filter=europe&filter=spain

Query params and fragments

Upvotes: 1

jburtondev
jburtondev

Reputation: 3263

Angular's paramMap should enable this.

You can subscribe to the url parameters and run what you wish on each route respectively. See the example below:

this.route.paramMap.subscribe(params => {
    if (params.get('username'))) {
        // Route to particular path...
        // Or do something else...
    }
});

Here are some additional resources:

Upvotes: 0

No you cant. You cannot have duplicate params in your routes. IF you do so, you can only get the last data that has duplicate in the url. In your case, it will return only asia and china

Upvotes: 0

Related Questions