简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM