繁体   English   中英

在从 authGuard 的 canActivate 接收到 false 时进行路由器重定向

[英]Making router redirect upon receiving false from authGuard's canActivate

我设置了多个身份验证防护并在 canActivate 中使用它们。 通常我有router.navigate(["/error",403])在守卫本身,但我已经开始组合不同的守卫所以例如我在某些组件中有守卫 A 和守卫 B 我使用 A 一些使用 B 和一些使用逻辑 A 或 B。这使得来自守卫内部的路由无法使用,当守卫返回错误路由时,路由不会做任何事情。 从我的守卫返回 false 后,我可以让 Angular 路由器重定向到我的/error/403页面吗? 我听说将通配符设置为 403 有效,但设置后我没有看到任何变化。 从看起来如果guard返回false angular不会做任何事情,我没有收到任何控制台消息并且页面不会重定向到任何地方。 我怎样才能改变这种行为?

canActivate可以返回,除了true / false ,一个UrlTree

  constructor(private router: Router) {}

  canActivate(snapshot: ActivatedRouteSnapshot): boolean | UrlTree {
    return someTest(snapshot) ? true : this.router.createUrlTree(['/', 'error', '403']);
  }

你总是可以扩展你的守卫并返回一个UrlTree 因此,任何共享逻辑都在您的抽象类中:

export class GuardA extends Guard403 implements CanActivate {
  contructor(router: Router) {
    super(router);
  }

  canActivate(): Observable<boolean | UrlTree> {
    return this.canThisReallyActivateA().pipe(
      map((canActivate) => canActivate || this.cantActivate;
    )
  }
}

export class GuardB extends Guard403 implements CanActivate {
  contructor(router: Router) {
    super(router);
  }

  canActivate(): Observable<boolean | UrlTree> {
    return this.canThisReallyActivateB().pipe(
      map((canActivate) => canActivate || this.cantActivate;
    )
  }
}

export abstract class Guard403 {
  readonly cantActivate = this.router.createUrlTree(['/errror', '403']);

  constructor(protected router: Router) {}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM