Does the order of the paths listed in app.module.ts file matters? For example...
RouterModule.forRoot([
{path:'',component:HomeComponent},
{path:'followers',component:GithubFollowersComponent},
{path:'followers/:username/:userid',component:GithubProfileComponent},
{path:'posts',component:PostsComponent},
{path:'**',component:NotFoundComponent}
])
vs..
RouterModule.forRoot([
{path:'',component:HomeComponent},
{path:'followers/:username/:userid',component:GithubProfileComponent},
{path:'followers',component:GithubFollowersComponent},
{path:'posts',component:PostsComponent},
{path:'**',component:NotFoundComponent}
])
I was watching a tutorial and it said that the order does matter.. but I tried it both ways and they both seem to work as expected...
If I move the wild card path( ** ) to the top then yes I do notice the difference. But for others does the order don't matter at all? Or am I missing something here?....
Their order is important because the Router uses a first-match wins strategy when matching routes, so more specific routes should be placed above less specific routes. List routes with a static path first, followed by an empty path route, which matches the default route.
Steps to detect route change in Angular application Urls. Import Router, Event, NavigationStart, NavigationEnd, NavigationError from '@angular/router'. And inject router in the constructor. Subscribe to the NavigationStart, NavigationEnd, NavigationError events of the router.
The two asterisks, ** , indicate to Angular that this routes definition is a wildcard route. For the component property, you can define any component in your application.
The other paths are completely different, so no, order does not matter for these. The routing engine won't confuse followers
and followers/:username/:userid
- as the Angular guide points out, :username
and :userid
are required parameters, so need to be present, as in followers/testuser/10
.
It does matter when two routes conflict tho, as in posts
and **
. The path /posts
will be matched by both routes, and first one wins.
This is why the wildcard is at the end. As a basic rule, always try to order by most specific to least specific.
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