Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
573 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

This simplified piece:

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

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...