How to wait for guards in Angular

If I point three guards along the route, it seems that all guards are assessed immediately.

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

I have a problem: I don't want to GuardTwo

run until GuardOne finishes. Is there a way to achieve this?

+3


source to share


1 answer


I don't think this is possible in 4.1.3. Here is the code that triggers 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 part:

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

      



launches all the guards in sequence, without waiting for the end of the previous one.

One possible solution would be to have one service that implements CanActivate

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

      

+5


source







All Articles