【问题标题】:Router canActivateChild with more than 1 guard路由器 canActivateChild 有超过 1 个保护
【发布时间】:2018-02-26 10:14:47
【问题描述】:

我正在使用多个 canActivateChild 守卫,如下所示:

{path: 'admin', canActivateChild : [AdminAuthGuard, EmployeeAuthGuard], children: adminRoutes }

下面是管理员守卫的定义:

canActivateChild() : boolean {
   const role = localStorage.getItem('role');
   if(role === 'admin') {
     return true;
   }
   else {
     return false;
   }
}

我有非常相似的员工警卫,我正在检查作为员工的角色。 上面代码的问题是:

  1. 如果我的第一个守卫返回 false,则根本不执行第二个守卫。
  2. 如果我的第一个守卫返回 true 而我的第二个守卫返回 false。这条路线当时也失败了。

注意:我的守卫是同步的,但我仍然面临这个问题。请告诉我如何解决?

实际的代码比这复杂得多。这只是获取帮助的示例代码。

【问题讨论】:

  • @Safiyya 我不想检查所有警卫。我的申请中有 10 个 gurds。使用共享服务将检查每个警卫。对于管理员路由,我只想检查两个警卫。

标签: angular angular-guards


【解决方案1】:

创建一个联合的保护来检查两个返回值的其他 2 个保护:

class CombinedGuard {
  constructor(private adminGuard: AdminAuthGuard, private employeeGuard: EmployeeAuthGuard) {}

  canActivate(r, s) {
        // defined your order logic here, this is a simple AND
        return this.adminGuard.canActivate(r, s) && this.employeeGuard.canActivate(r,s)
  }
}

然后在您的路由中使用该 CombinedGuard :

{path: 'admin', canActivateChild : [CombinedGuard], children: adminRoutes }

灵感来自How to wait for guards in Angular

【讨论】:

  • 还有其他解决方案吗?似乎是解决方案,但在这里我需要创建很多组合守卫,因为我必须在这里有很多排列?
  • 您可以为每个案例使用返回和Array<CanActivate> 的工厂,并在组合防护中返回array.map(g => g.canActivate(r,s))。这样您就可以将排列逻辑与激活逻辑分开
  • 这有意义吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-02
  • 2014-10-26
  • 2018-01-07
  • 1970-01-01
  • 2021-09-28
  • 2021-02-13
  • 2019-02-10
相关资源
最近更新 更多