Angular 角度2路由器可激活身份验证保护

Angular 角度2路由器可激活身份验证保护,angular,typescript,angular2-routing,router,canactivate,Angular,Typescript,Angular2 Routing,Router,Canactivate,在过去的4个小时里,我一直在寻找这个问题,但找不到任何答案 我写了几个AuthGuard,我想告诉路由器,如果其中一些是真的,它应该给予许可,但是angular 2路由器检查每个guard是否都是真的,然后给予许可,否则它会阻止链接,有什么好办法吗?我可以写几个认证守卫,但我认为这不是一个好主意 例如,我希望管理员和超级用户可以访问/profile页面,但我不希望普通用户访问/profile页面您可以将您的保护插入一个父保护中,然后自己控制: @Injectable() clas

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

我写了几个AuthGuard,我想告诉路由器,如果其中一些是真的,它应该给予许可,但是angular 2路由器检查每个guard是否都是真的,然后给予许可,否则它会阻止链接,有什么好办法吗?我可以写几个认证守卫,但我认为这不是一个好主意


例如,我希望管理员和超级用户可以访问
/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 
  ...
}

当然,您也可以在其他路径中使用
guard1
guard2

您可以将您的保护注入一个父保护中,然后自己控制:

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

当然,您可以在其他路由中使用
guard1
guard2

您可以在身份验证保护中使用
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
     }
}
导出类AuthenticationGuard实现CanLoad{
canLoad(路径:路径):可观察的|承诺|布尔值{
//在此处,请要求您的身份验证服务检查当前用户是否具有此路由的权限
}
}

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

您可以在身份验证保护中使用
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
     }
}
导出类AuthenticationGuard实现CanLoad{
canLoad(路径:路径):可观察的|承诺|布尔值{
//在此处,请要求您的身份验证服务检查当前用户是否具有此路由的权限
}
}

我希望这有帮助,请让我知道更多问题。

您也可以使用guard来做这件事,例如检查即将到来的用户是admin,然后返回true或false等,您可以逻辑处理。您也可以使用guard来做这件事,例如检查即将到来的用户是admin,然后返回true,否则返回false等,您可以逻辑地处理它