11

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

psj01
  • 3,075
  • 6
  • 32
  • 63

1 Answers1

14

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.

Rhumborl
  • 16,349
  • 4
  • 39
  • 45
  • Does the order which I list {path:'followers/:username/:userid',component:GithubProfileComponent} and {path:'followers',component:GithubFollowersComponent} matter? I feel like the one with username and user id should come first.. otherwise it will always show GithubFollowersComponent and you will never get GithubProfileComponent... But that doesn't seem to be the case here... – psj01 Apr 20 '18 at 19:22
  • 1
    @psj01 I've updated the answer to explain how those 2 routes are different from each other, so order does not matter. Still, I would probably put the one with username and id first anyway to avoid any doubt. – Rhumborl Apr 20 '18 at 21:57
  • 1
    Just a note here, Angular outlines if order matters [here](https://angular.io/guide/router#route-order). – Dane Brouwer Nov 12 '21 at 08:49