【问题标题】:How to wait for guards in Angular如何在 Angular 中等待守卫
【发布时间】:2017-11-11 15:22:59
【问题描述】:

如果我在一条路线上指定三个警卫,似乎所有警卫都会立即评估。

{path: '', component: OptionsComponent, canActivate: [ GuardOne, GuardTwo, GuardThree]}

我的问题是我不希望 GuardTwo 在 GuardOne 完成之前运行。有什么方法可以实现吗?

【问题讨论】:

  • @maddockst 我想知道是什么迫使您需要同步加载警卫?你能详细说明一下吗?
  • @Z.Bagley 我正在使用儿童路线,并希望为所有这些儿童使用警卫。
  • @maddockst,我的回答有帮助吗?
  • @Maximus 还没有机会使用它,我会更新它

标签: javascript angular rxjs rxjs5


【解决方案1】:

我认为这在 4.1.3 中是不可能的。 Here 是运行守卫的代码:

  private runCanActivate(future: ActivatedRouteSnapshot): Observable<boolean> {
    const canActivate = future._routeConfig ? future._routeConfig.canActivate : null;
    if (!canActivate || canActivate.length === 0) return of (true);
    const obs = map.call(from(canActivate), (c: any) => {
      const guard = this.getToken(c, future);
      let observable: Observable<boolean>;
      if (guard.canActivate) {
        observable = wrapIntoObservable(guard.canActivate(future, this.future));
      } else {
        observable = wrapIntoObservable(guard(future, this.future));
      }
      return first.call(observable);
    });
    return andObservables(obs);
  }

这个简化的片段:

// array of all guards
canActivate.map((guard)=>{
     observable = guard.canActivate()
})

按顺序运行所有守卫而不等待前一个完成。

一种可能的解决方案是让一个服务实现CanActivate 并结合其他守卫:

class Combined {
  constructor(private gA: GuardA, private gB: GuardB) {}

  canActivate(r, s) {
        return gA.canActivate(r, s).then(()=>{ return gB.canActivate() });
  }
}

... 
{path: '', component: OptionsComponent, canActivate: [ Combined ]}

【讨论】:

  • 那么是否可以在单独的服务中同步构建它们,然后映射到同步构建它们的那个服务中?
  • 可靠的答案,但你知道什么时候需要这种情况吗?
  • 什么意思?既然你问了这个问题,你可能有这样的情况:)
  • 我没有问,当你的答案出现时,我正在为 OP 做一个答案,我只是好奇 :)
  • @Z.Bagley,啊,我明白了,对不起。让我们问问OP :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-01-10
  • 1970-01-01
  • 2019-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多