【问题标题】:Angular2 run Guard after another guard resolvedAngular2在另一个警卫解决后运行警卫
【发布时间】:2017-05-08 21:31:38
【问题描述】:

在我的项目中,我有两个警卫。 AuthGuard 和 PermissionGuard。我需要首先运行 AuthGuard,当它解决时,如果为 true,permissionGuard 开始,但现在这个守卫正在并行运行,permissionGuard 不能正常工作。我在这个问题上使用的方法是我在权限保护中调用了 AuthGuard CanActivate 方法,但我认为有一个更好的方法可以做到这一点。

【问题讨论】:

  • 也许this answer 可以帮助你。我认为他也有同样的问题。
  • 谢谢,你提到的问题的答案和我一样,但正如我所说,我认为可能存在更好的方法。
  • @hosseinahmadi。您还需要这方面的帮助吗?
  • 那个答案重复了现有的守卫。我们可以将另一个守卫的实例传递给新守卫吗?

标签: javascript angular angular2-routing


【解决方案1】:

我见过的最好的方法是在子路由上公开路由器防护。这是working example

{
  path:'', canActivate:[AuthorizationService1], 
    children: [
      {
        path:'', canActivate:[AuthorizationService2],component: HomeComponent
      }
    ]
}

【讨论】:

    【解决方案2】:

    不幸的是,守卫不能真正相互依赖。你可以按照另一个人的建议做一个在父路由上做一个,在子路由上做一个,或者我的偏好只是让第三个后卫依次运行这两个检查,所以我不需要弄乱我的路线,假设它们被实现为可观察对象:

    @Injectable({ providedIn: 'root' })
    export class AuthAndPermissionGuard implements CanActivate {
      constructor(private authGuard: AuthGuard, permGuard: PermGuard) { }
      canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
        return this.authGuard.canActivate(next, state).pipe(
          switchMap(isAuthed => isAuthed ? this.permGuard.canActivate(next, state) : of(false))
        );
      }
    }
    

    【讨论】:

      【解决方案3】:

      你可以像这样将两个gurd传递给路由:

      {
         path:'', canActivate:[AuthorizationGuards1,AuthorizationGuards2] 
      }
      

      AuthorizationGuards1成功AuthorizationGuards2激活后,这两个守卫之间的关系就像AuthorizationGuards1 && AuthorizationGuards2条件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-01-30
        • 2017-04-21
        • 1970-01-01
        • 1970-01-01
        • 2014-06-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多