From the Angular documentationcanActivate上,似乎只有当canActivate函数最终返回canActivate时,您才能使用true保护来允许继续进行路由。
有没有办法说,“只有当canActivate类的计算结果为false”时,才继续此路由?
例如,为了不允许登录的用户访问登录页,我尝试了此操作,但没有成功:

export const routes: Route[] = [
    { path: 'log-in', component: LoginComponent, canActivate: [ !UserLoggedInGuard ] },

我在控制台上看到这个错误:
ERROR Error: Uncaught (in promise): Error: StaticInjectorError[false]:
  StaticInjectorError[false]:
    NullInjectorError: No provider for false!
Error: StaticInjectorError[false]:
  StaticInjectorError[false]:
    NullInjectorError: No provider for false!

最佳答案

你问题中有趣的是公式:
有没有办法说,“只有在
canActivate类的计算结果为false“?
以及你如何表达“直观”的解决方案:

{ path: 'log-in', component: LoginComponent, canActivate: [ !UserLoggedInGuard ] },

也就是说,你需要negate的结果
让我们考虑以下UserLoggedInGuard@canActivate的实现:
@Injectable()
export class UserLoggedInGuard implements CanActivate {
   constructor(private _authService: AuthService) {}

   canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return this._authService.isLoggedIn();
    }
}

接下来,让我们看看@mike提出的解决方案
@Injectable()
export class NegateUserLoggedInGuard implements CanActivate {
    constructor(private _authService: AuthService) {}

   canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        return !this._authService.isLoggedIn();
    }
}

现在,这种方法是可以的,但是与UserLoggedInGuard的(内部)实现紧密耦合。如果由于某种原因UserLoggedInGuard的实现发生更改,UserLoggedInGuard@canActivate将中断。
我们怎么能避免呢?简单的滥用依赖注入:
@Injectable()
export class NegateUserLoggedInGuard implements CanActivate {
  constructor(private _userLoggedInGuard: UserLoggedInGuard) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
     return !this._userLoggedInGuard.canActivate(route,state);
  }
}

现在这正是你所表达的
canActivate: [ !UserLoggedInGuard ]

最好的部分是:
它与NegateUserLoggedInGuard
可以展开以操作多个UserLoggedInGuard类的结果

关于angular - 如何使用Angular的canActivate否定后卫的结果?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48197067/

10-12 07:00