Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 CanActivate guard for all routes except one

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

like image 778
Sergey Tyupaev Avatar asked Nov 29 '16 18:11

Sergey Tyupaev


1 Answers

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.

like image 77
Günter Zöchbauer Avatar answered Oct 21 '22 20:10

Günter Zöchbauer