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:
I can change path. blog/id and blogs/moo.
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?
According to Angular official documentation
refer to this
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With