我有一个angular 4应用程序,并实现了一个防护来处理身份验证。我们有不同的模块,它们使用工厂来创建我们称之为主题服务的东西。每个模块都是自包含的应用程序,具有自己的样式和安全性。每个模块都告诉ThemeService用户必须访问的角色,并且该守卫工作正常。
这是守卫:
export class AuthenticatedGuard implements CanActivate { constructor (private memSrv:MembershipService, private themeSrv:ThemeService,private router:Router ) { } canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapshot ): Observable<boolean> | Promise<boolean> | boolean { return this.memSrv.GetCurrentUser() .map(u => { if (!u) { this.router.navigate([this.themeSrv.LoginUrl]); return false; } var isAuth = u.Capabilities.some(s => s === this.themeSrv.AuthCapability); if (isAuth) { return true; } else { //TODO: This is an unauthorized but authenticated user it should go to an unauthorized page this.router.navigate(["/Unauthorized", { url: state.url }]); return false; } } ); } }
我现在有一个模块,其中有一些路由需要使用不同的角色进行保护。我的问题是如何将每个路由必须检查的角色传递给AuthenticationGuard。我不想为我们要检查的每个角色创建不同的守卫。
下面是我的路由配置的一个片段
{ path: "", component: Component.MainComponent, children: [ { path: 'attachmentsTest', component: Component.AttachmentsTestComponent, }, { path:"home", component: Component.HomeComponent, canActivate: [AuthenticatedGuard], resolve: { user: CurrentUserResolver } },
是的,您可以将值输入到路由配置中,以便稍后使用 data 所有物以下是一个示例:
data
@NgModule({ imports: [ RouterModule.forChild([ { path: 'products', component: ProductListComponent, data: { pageTitle: 'Product List' } }, { path: 'products/:id', component: ProductDetailComponent }, { path: 'products/:id/edit', component: ProductEditComponent } ]) ], // ...
请注意此处的数据属性。
然后可以使用如下语法读取该属性:
this.pageTitle = this.route.snapshot.data['pageTitle'];