Angular 2 router canActivate Auth Guard

Angular 2 router canActivate Auth Guard

过去 4 小时我一直在搜索此内容,但找不到任何答案。

我写了几个 Authguards,我希望能够告诉路由器,如果其中一些是真的,它应该授予权限,但是 angular2 路由器检查每个守卫是否是真的,然后授予权限,否则会阻塞link,请问有什么好的方法吗?我可以写几个身份验证守卫,但我认为那不是个好主意。

例如,我希望管理员和超级用户可以访问 /profile 页面,但我不希望普通用户访问 /profile 页面

你可以将你的守卫注入一个父守卫并自己控制:

    @Injectable()
    class Guard implements CanActivate {

      constructor(private guard1: Guard1, private guard2: Guard2) {}

      canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot):boolean {
        // I'm assuming that your guard1.canActivate and guard2.canActivate return boolean
        return guard1.canActivate() || guard2.canActivate();
      }
    }

在你的路由配置中只使用 Guard guard:

{
  path : 'route',
  canActivate : Guard 
  ...
}

当然你可以在其他路线中使用guard1guard2

您可以在您的身份验证守卫中使用 CanLoad 界面。例如,假设您的路线就是这样;

{
     path: 'profile',
     component: 'ProfileComponent',
     canLoad: [
          AuthenticationGuard
     ]
}

在您的 AuthenticationGuard 中,实现 CanLoad 接口。如果用户没有此 link 的权限,则不会加载此路由的模块。

export class AuthenticationGuard implements CanLoad {
     canLoad(route: Route): Observable<boolean> | Promise<boolean> | boolean {
          //in here ask your authentication service to check current user has permission for this route
     }
}

希望对您有所帮助,如有其他问题,请告诉我。