Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Routing in angular - Does the order of paths matter?

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?....

like image 350
psj01 Avatar asked Apr 20 '18 19:04

psj01


People also ask

Does the order of routes matter in Angular?

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.

How does Angular determine routing?

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.

What does the * * path in Angular router do?

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.


1 Answers

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.

like image 200
Rhumborl Avatar answered Nov 03 '22 01:11

Rhumborl