本文介绍了如何在 Angular 中等待守卫的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If i specify three guards on a route, it seems as though all guards are evaluated immediately.

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

我遇到的问题是我不希望 GuardTwo 在 GuardOne 完成之前运行.有什么办法可以做到这一点吗?

The problem I have is I don't want GuardTwo to run until GuardOne has finished. Is there any way to achieve this?

推荐答案

我认为这在 4.1.3 中是不可能的.这里是运行守卫:

I don't think that's possible in the 4.1.3. Here is the code that runs the guards:

  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()
})

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

runs all guards in a sequence without waiting for the previous to finish.

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

One possible solution would be to have one service that implements CanActivate and combines other guards:

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

这篇关于如何在 Angular 中等待守卫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 11:22