Multiple canActivate guards all run when first fails

前端 未结 6 1286
借酒劲吻你
借酒劲吻你 2020-12-02 15:32

I have a route with two canActivate guards (AuthGuard and RoleGuard). The first (AuthGuard) checks to see if the user is

6条回答
  •  孤街浪徒
    2020-12-02 16:07

    This is due to the fact you are returning a Promise instead of just a boolean. If you were to just return a boolean it wouldn't check the RoleGuard. I would guess this is either a bug in angular2 or an expected result of async requests.

    You can however resolve this with your example by only using RoleGuard for urls where a certain Role is required, because I guess you need to be logged in to have a role. In that case you can change your RoleGuard to this:

    @Injectable()
    export class RoleGuard implements CanActivate {
      constructor(private _authGuard: AuthGuard) {}
    
      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise {
        return this._authGuard.canActivate(route, state).then((auth: boolean) => {
          if(!auth) {
            return false;
          }
          //... your role guard check code goes here
        });
      }
    }
    

    Update
    In the latest Angular version (currently v8.x) - Even if both Guard will return false - they will still be both executed. (behavior was aligned between different return values)

提交回复
热议问题