我有一条有两个人的路线canActivate
警卫(AuthGuard
and RoleGuard
)。首先 (AuthGuard
)检查用户是否已登录,如果没有,则重定向到登录页面。第二个检查用户是否定义了允许查看页面的角色,如果没有,则重定向到未经授权的页面。
canActivate: [ AuthGuard, RoleGuard ]
...
export class AuthGuard implements CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
...
this.router.navigate(['/login']);
resolve(false);
}
export class RoleGuard implements CanActivate {
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
...
this.router.navigate(['/unauthorized']);
resolve(false);
}
问题是,当我访问路线并且未登录时,我点击了AuthGuard
,失败并告诉路由器导航到/login
。然而,尽管AuthGuard
失败了,则RoleGuard
无论如何运行然后导航到/unauthorized
.
在我看来,如果第一个守卫失败了,那么运行下一个守卫是没有意义的。有什么办法可以强制执行这种行为吗?
在最新的 Angular 版本中,即使两个守卫都回来了false
,两者仍将被执行。
但是,您可以通过仅使用示例来解决此问题RoleGuard
对于某个特定的网址Role
是必需的,因为我猜您需要登录才能拥有角色。在这种情况下,您可以更改您的RoleGuard
对此:
@Injectable()
export class RoleGuard implements CanActivate {
constructor(private _authGuard: AuthGuard) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
return this._authGuard.canActivate(route, state).then((auth: boolean) => {
if(!auth) {
return false;
}
//... your role guard check code goes here
});
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)