Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameterised Routes in Angular 5

Based on LINK from here - in my application I've routing:

const routes: Routes = [
 { path: 'blog/:id', component: BlogComponent },
 { path: 'blog/moo', component: MooComponent },
];

And there is information that:

If we visited /blog/moo we would show MooComponent even though it matches the path for the first blog/:id route as well.

Important Non-parameterised routes take precedence over parameterised routes.

Unfortunately it doesn't work like that. If I will go to url blog/moo then routing will treat moo as Id and will open BlogComponent.

I wondering how can I solve I have 2 ideas:

  1. I can change path. blog/id and blogs/moo.

  2. I can use UrlMatcher but it could be slightly problematic when I'll change previos url segments. So this function should be very well prepared.

What do you think? Any ideas?

like image 253
DiPix Avatar asked Mar 07 '23 10:03

DiPix


2 Answers

According to Angular official documentation refer to this

The router selects the route with a first match wins strategy.

  • The router selects the route with a first match wins strategy. Wildcard routes are the least specific routes in the route configuration. Be sure it is the last route in the configuration.

  • 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. In the configuration above, routes with a static path are
    listed first, followed by an empty path route, that matches the
    default route. The wildcard route comes last because it matches every URL and should be selected only if no other routes are matched first.

Even this explains the same regarding the route prioritization

So you should keep your routes in reverse order:

const routes: Routes = [
 { path: 'blog/moo', component: MooComponent },
 { path: 'blog/:id', component: BlogComponent },
];

I want to highlight a point from above statements:

Note:

More specific routes should be placed above less specific routes.

Since 'blog/moo' is more specific, you need to place it above 'blog/:id'

I have created a PLUNKER for your example

like image 160
Sravan Avatar answered Mar 16 '23 12:03

Sravan


in

const routes: Routes = [
 { path: 'blog/:id', component: BlogComponent },
 { path: 'blog/moo', component: MooComponent },
];

try writing it as :

const routes: Routes = [
 { path: 'blog/moo', component: MooComponent },
 { path: 'blog/:id', component: BlogComponent },

];

It should work now.In angular there is significance in the order you write the routes.

like image 23
Vivek P Rajeev Avatar answered Mar 16 '23 13:03

Vivek P Rajeev