Angular2 Can激活除一条以外的所有路径的防护 [英] Angular2 CanActivate guard for all routes except one

查看:64
本文介绍了Angular2 Can激活除一条以外的所有路径的防护的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们可以对位于一个模块中的路由进行分组.像这样:

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 }
    ],
  }
}

,并在防护中检查用户是否已登录. 如果尚未登录且当前路由为login,则仍允许它.

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.

这篇关于Angular2 Can激活除一条以外的所有路径的防护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆