子项 Angular 路由中的不同 RoleGuard

Different RoleGuard in a Child Item Angular Routing

我想知道您是否使用 RoleGuard 来检查是否有人可以激活路径,并且您希望在子项中使用不同的 RoleGuard 是可能的:

我已经尝试过,但我无法访问具有不同 RoleGuard 的路径

{
    path: 'admin',
    canActivate: [AdminGuard],
    children: [
        { path: '', redirectTo: 'test', pathMatch: 'full'},
        { path: 'test', component: MasterDataComponent},
        { path: 'test/subtest', component: ObjectsTypeComponent },
        { path: 'test/subtest/:operation', component: ObjectsTypeDetailComponent },
        { path: 'test/subtest/:operation/:id', component: ObjectsTypeDetailComponent },
        { path: 'test/money', component: DivisesComponent, canActivate: [OperatorGuard] } 
}

所以,只有管理员可以进入这个路径,但我想让操作员进入路径 test/money。

谢谢指教。

您正在尝试在已有 Guard 的路线内使用 Guard。如果守卫是 "enhancing security"(又名添加属性),这会没问题。

但是,一旦您想覆盖保护属性,您有两个选择:

  1. 将守卫分别添加到每条路线。
  2. 添加另一条路线来覆盖第一条路线(您必须编写 OperatorOrAdminGuard)。
{
    path: 'admin',
    canActivate: [AdminGuard],
    children: [
            { path: '', redirectTo: 'test', pathMatch: 'full'},
            { path: 'test', component: MasterDataComponent},
            { path: 'test/subtest', component: ObjectsTypeComponent },
            { path: 'test/subtest/:operation', component: ObjectsTypeDetailComponent },
            { path: 'test/subtest/:operation/:id', component: ObjectsTypeDetailComponent },
    ],
},
{
    path: 'admin/test/money',
    component: DivisesComponent, 
    canActivate: [OperatorOrAdminGuard]
}

您可以使用 GuardFactory,而不是为不同的用户创建多个守卫。在这里解释:Pass parameter into route guard

然后,像这样使用它:

{ 
   path: 'admin/test/money, 
   component: DivisesComponent,
   canActivate: RoleGuard,
   data: {roles: ['Operator', 'Admin']}
}