I have multiple authentication guards setup and use them in canActivate. Normally I have had router.navigate(["/error",403])
in guard itself, but I have started combining different guards so for example i have guard A and guard B in some component i use A some use B and som use logical A OR B. this makes routing from inside guard unusable, when guard returns false routing doesn't do anything. Can I make angular router redirect to my /error/403
page upon returning false from my guards? I've heard that setting up wildcard to 403 works but I haven't seen any change after setting it up. From what it seems if guard returns false angular doesn't do anything, i don't get any console message and page doesn't redirect anywhere. How can I change this behaviour?
canActivate
can return, besides true
/ false
, an UrlTree
:
constructor(private router: Router) {}
canActivate(snapshot: ActivatedRouteSnapshot): boolean | UrlTree {
return someTest(snapshot) ? true : this.router.createUrlTree(['/', 'error', '403']);
}
You can always extend your guards and return an UrlTree
. So any shared logic goes in your abstract class:
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) {}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.