如何在Angular等待守卫

mad*_*kst 7 javascript rxjs rxjs5 angular

如果我在路线上指定三名警卫,似乎所有警卫都会立即进行评估.

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

我遇到的问题是我不希望GuardTwo在GuardOne完成之前运行.有没有办法实现这个目标?

Max*_*kyi 11

我不认为这在4.1.3中是可能的.以下是运行警卫的代码:

  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);
  }
Run Code Online (Sandbox Code Playgroud)

这个简化的部分:

// array of all guards
canActivate.map((guard)=>{
     observable = guard.canActivate()
})
Run Code Online (Sandbox Code Playgroud)

按顺序运行所有警卫,无需等待前一个完成.

一种可能的解决方案是拥有一个实现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 ]}
Run Code Online (Sandbox Code Playgroud)