我有一个角度4应用程序,并已实现一个警卫来处理身份验证。我们有不同的模块,使用工厂来创建我们称之为ThemeService的模块。每个模块都是自包含的应用程序,具有自己的样式和安全性。每个模块告诉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传递必须为每条路由检查的角色。我不想为我们想要检查的每个角色创建一个不同的后卫。
Bellow是我路线配置的片段
{
path: "",
component: Component.MainComponent,
children:
[
{
path: 'attachmentsTest',
component: Component.AttachmentsTestComponent,
},
{
path:"home",
component: Component.HomeComponent,
canActivate: [AuthenticatedGuard],
resolve: {
user: CurrentUserResolver
}
},
答案 0 :(得分:1)
Yes, you can put values into the route configuration to pull out later using the data
property. Here is an example:
@NgModule({
imports: [
RouterModule.forChild([
{
path: 'products',
component: ProductListComponent,
data: { pageTitle: 'Product List' }
},
{ path: 'products/:id', component: ProductDetailComponent },
{ path: 'products/:id/edit', component: ProductEditComponent }
])
], // ...
Notice the data property here.
You can then read that property using syntax like this:
this.pageTitle = this.route.snapshot.data['pageTitle'];