我正在构建一个基于角色的角色,即每个角色(例如Admin)都有其自己的布局模块,即AdminLayoutModule和MOBIADMIN(角色)具有其自己的布局MobiLayoutModule。我系统中的每条路线都由auth guard保护。在我的应用程序中,我有两个组件在我的有角项目中 1)UsersListComponent 2)UserProfileComponent 我想在上述两个模块之间共享它。要实现此目的,我创建了一个共享模块,并在共享模块中导出了这两个组件,然后将该模块导入了AdminLayoutModule和MobiLayoutModule中。当我登录时,一切都工作得很好使用admin我可以通过使用admin角色来访问两个组件,但是当我通过mobiadmin登录时,我的身份验证卫士不允许我访问这两个组件。我不知道我在做什么错,下面如何解决此问题是我的代码
我正在传递预期角色的app.routing.ts文件
const routes: Routes =[{
path: '',
component: AdminLayoutComponent,
canActivate:[AuthGuardService],
data: {
expectedRole: 'Admin'
},
children: [
{
path: '',
loadChildren: './layouts/admin-layout/admin-layout.module#AdminLayoutModule'
}]},
{
path:'',
component:MobiLayoutComponent,
canActivate:[AuthGuardService],
data: {
expectedRole: 'Mobilink'
},
children:[
{
path:'',
loadChildren:'./layouts/mobi-layout/mobi-layout.module#MobiLayoutModule'
}
]
},]
下面是我的admin-layout-routing.ts的代码
export const AdminLayoutRoutes: Routes = [{ path: 'users-list',component:UsersListComponent},
{ path: 'dashboard', component: DashboardComponent },
{ path: 'roles', component:RolesComponent},
{ path: 'user-profile', component: UserProfileComponent },
{ path:'user-profile/:id', component:UserProfileComponent},]
及以下是我的mobi-layout-routing.ts代码
export const MobiLayoutRoutes:Routes=[
{path:'mobilink_dashboard',component:MobiDashboardComponent},
{path:'**',redirectTo:'mobilink_dashboard',pathMatch:'full'},
{ path: 'user-profile', component: UserProfileComponent },
{ path:'user-profile/:id', component:UserProfileComponent},
];
和authguard.ts的代码
canActivate(route:ActivatedRouteSnapshot):boolean{
alert("expected role is :: "+route.data.expectedRole);
const expectedRole = route.data.expectedRole;
const token = localStorage.getItem('token');
const tokenPayload = decode(token);
const user_role=tokenPayload['role'].toString();
alert("User Role Is "+user_role);
if (
!this.auth.isAuthenticated() ||
user_role!== expectedRole
) {
localStorage.removeItem('token');
localStorage.removeItem('user');
this.router.navigate(['login']);
return false;
}
return true;
}