首页 文章

Angular 2路由器可以激活Auth Guard

提问于
浏览
0

我一直在寻找这个过去4个小时,但找不到任何答案 .

我写了几个Authguards,我希望能告诉路由器,如果其中一些是真的它应该给予许可,但有角度的2路由器检查每个守卫是否为真然后给予许可,否则它将阻止链接,是这有什么好办法吗?我可以写几个身份验证保护,但我认为这不是一个好主意 .

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

2 回答

  • 1

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

    @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 .

  • 1

    您可以在身份验证防护中使用 CanLoad 接口 . 例如,假设您的路线就是这样;

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

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

    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
         }
    }
    

    我希望它有所帮助,请让我知道更多问题 .

相关问题