【问题标题】:Angular 2 router canActivate Auth GuardAngular 2 路由器可以激活 Auth Guard
【发布时间】:2017-03-23 16:24:22
【问题描述】:

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

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

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

【问题讨论】:

  • 你也可以使用guard来做到这一点,例如检查即将到来的用户是admin,SU然后返回true,否则返回false等你可以逻辑处理

标签: angular typescript angular2-routing router canactivate


【解决方案1】:

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

    @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();
      }
    }

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

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

当然你也可以在其他路由中使用guard1和guard2。

【讨论】:

    【解决方案2】:

    您可以在身份验证保护中使用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
         }
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-16
      • 1970-01-01
      • 2016-12-25
      • 2017-11-11
      • 1970-01-01
      相关资源
      最近更新 更多