你如何使用Angular的canActivate来否定守卫的结果?

前端之家收集整理的这篇文章主要介绍了你如何使用Angular的canActivate来否定守卫的结果?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
From the Angular documentation on canActivate,似乎你只能使用canActivate防护来允许在canActivate函数最终返回true时继续进行路由.

有没有办法说,“只有在canActivate类评估为false时才进入这条路线”?

例如,为了不允许登录用户访问登录页面,我尝试了这个但是它不起作用:

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

我在控制台中遇到此错误

  1. ERROR Error: Uncaught (in promise): Error: StaticInjectorError[false]:
  2. StaticInjectorError[false]:
  3. NullInjectorError: No provider for false!
  4. Error: StaticInjectorError[false]:
  5. StaticInjectorError[false]:
  6. NullInjectorError: No provider for false!
你问题中有趣的是配方:

Is there some way to say,“only proceed to this route if the
canActivate class evaluates to false” ?

以及您如何表达“直观”的解决方案:

  1. { path: 'log-in',

基本上说,你需要否定UserLoggedInGuard @ canActivate的结果

让我们考虑UserLoggedInGuard的以下实现:

  1. @Injectable()
  2. export class UserLoggedInGuard implements CanActivate {
  3. constructor(private _authService: AuthService) {}
  4.  
  5. canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): boolean {
  6. return this._authService.isLoggedIn();
  7. }
  8. }

接下来,让我们看看@Mike提出的解决方

  1. @Injectable()
  2. export class NegateUserLoggedInGuard implements CanActivate {
  3. constructor(private _authService: AuthService) {}
  4.  
  5. canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): boolean {
  6. return !this._authService.isLoggedIn();
  7. }
  8. }

现在,方法还可以,但与UserLoggedInGuard的(内部)实现紧密相关.如果由于某种原因UserLoggedInGuard @ canActivate的实现发生了变化,NegateUserLoggedInGuard将会中断.

我们怎么能避免这种情况?简单的滥用依赖注入:

  1. @Injectable()
  2. export class NegateUserLoggedInGuard implements CanActivate {
  3. constructor(private _userLoggedInGuard: UserLoggedInGuard) {}
  4.  
  5. canActivate(route: ActivatedRouteSnapshot,state: RouterStateSnapshot): boolean {
  6. return !this._userLoggedInGuard.canActivate(route,state);
  7. }
  8. }

现在这正是你所表达的

  1. canActivate: [ !UserLoggedInGuard ]

最好的部分:

>它与UserLoggedInGuard的内部实现紧密耦合>可以扩展以操纵多个Guard类的结果

猜你在找的Angularjs相关文章