9

I know that we can group routes located in one module. Like that:

canActivate: [AuthGuard],
    children: [
      {
        path: '',
        children: [
          { path: 'crises', component: ManageCrisesComponent },
          { path: 'heroes', component: ManageHeroesComponent },
          { path: '', component: AdminDashboardComponent }
        ],
      }

But I should add that guard to each module's routing file. And I have many of them.

I want that the user can not go to any route except one (login route) if he is not authorized.

What is the right way to add guard to all of them??

Sergey Tyupaev
  • 1,264
  • 9
  • 23

1 Answers1

12

You can use a componentless empty path parent route with the guard

{ path: '', canActivate: [AuthGuard],  children: [
  {
    path: '',
    children: [
      { path: 'crises', component: ManageCrisesComponent },
      { path: 'heroes', component: ManageHeroesComponent },
      { path: '', component: AdminDashboardComponent }
    ],
  }
}

and in the guard check if the user is logged in. If not logged in and the current route is login then still allow it.

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 2
    What if all child routes in other files?? All modules have their own routing files. – Sergey Tyupaev Nov 29 '16 at 18:52
  • That should still work. I haven't used that myself yet. If it doesn't work, you can try to add the guard also to `canActivateChild`. – Günter Zöchbauer Nov 29 '16 at 18:54
  • What is the point of the inner componentless empty path? Why not just add the children to the outer path directly? Besides why would you use canActivate instead of canActivateChildren? – Aides May 08 '17 at 07:36
  • The point of the inner `''` is to make it the default route. The componentless root route is to be able to add `canActivate: [AuthGuard]` to only a single route and affect all routes. – Günter Zöchbauer May 08 '17 at 07:38