angular - 受身份验证服务保护的多个布局路线无法正常工作
问题描述
在我的 Angular 应用程序中,我为三个不同的用户提供了三种不同的布局 adminlayout for admin xyzlayout for company customerlayout for Customer
我已经为上述所有用户设置了三个不同的模块和路由模块,然后分别在应用程序主模块中导入了每个模块。管理员和公司角色一切正常,但是一旦我使用客户角色登录,我就会遇到一个奇怪的问题登录我被路由到 customer_dashboard 这很好但是当我导航侧边栏时系统将我注销,因为预期的角色与在我的 authguard 服务类中实现的当前角色不匹配。但是一旦我删除我的 xyzlayout 路由customerlayout 开始正常工作
下面给出的是我的 1)app.routing.module.ts 代码 2)auth 保护服务文件代码 3)login component.ts 代码
const routes: Routes =[
{
path: '',
redirectTo:'/login',
pathMatch:'full',
},
{
path:'login',
component:LoginComponent,
canActivate:[LoginGuard]
},
{
path: '',
component: AdminLayoutComponent,
canActivate:[AuthGuardService],
data: {
expectedRole: 'Admin'
},
children: [
{
path: '',
loadChildren: './layouts/admin-layout/admin-
layout.module#AdminLayoutModule'
}]},
{
path:'',
component:CustomerLayoutComponent,
canActivate:[AuthGuardService],
data: {
expectedRole: 'Customer'
},
children:[
{
path:'',
loadChildren:'./layouts/customer-layout/customer-
layout.module#CustomerLayoutModule'
}
]
},
{
path:'',
component:MobiLayoutComponent,
canActivate:[AuthGuardService],
data: {
expectedRole: 'Company'
},
children:[
{
path:'',
loadChildren:'./layouts/mobi-layout/mobi-layout.module#MobiLayoutModule'
}
]
},
//{ path:'**',redirectTo:'login',pathMatch:'full'}
];
@NgModule({
imports: [
CommonModule,
BrowserModule,
NgxUiLoaderModule.forRoot(ngxUiLoaderConfig),
RouterModule.forRoot(routes),
],
exports: [
],
})
export class AppRoutingModule { }
--------auth.guard.service.ts--------
export class AuthGuardService implements CanActivate {
constructor(public auth:AuthService,public router:Router) {
}
canActivate(route:ActivatedRouteSnapshot):boolean{
const expectedRole = route.data.expectedRole;
const token = localStorage.getItem('token');
const tokenPayload = decode(token);
const user_role=tokenPayload['role'].toString();
console.log("User Role Is "+user_role);
console.log("Expected Role Is"+expectedRole);
if (
!this.auth.isAuthenticated() ||
user_role!== expectedRole
) {
localStorage.removeItem('token');
localStorage.removeItem('user');
this.router.navigate(['login']);
return false;
}
return true;
}
}
--------登录.ts.--------
if(res['user'].role.toLowerCase()=='admin')
{
this.router.navigate(['/dashboard']);
}
else if(res['user'].role.toLowerCase()=='customer')
{
this.router.navigate(['/customer_dashboard']);
}
else if(res['user'].role.toLowerCase()=='company')
{
this.router.navigate(['/company_dashboard']);
}
解决方案
推荐阅读
- composer-php - TYPO3 8.7.16:扩展中的类不可用
- eslint - 未使用 var 的 ESLint 配置
- cordova-plugins - 添加 Ionic cordova-plugin-facebook4 后应用程序在启动时崩溃
- elasticsearch - Kibana 中未显示 APM 标签/标签
- angular - 我需要从 firestore 集合中获取数组而不是对象
- facebook - FB Ads Insights API:使用凭据获取访问令牌
- html - 任意宽度的垂直导航栏固定在左边。如何填充主要内容?
- c# - 使用 Appium 驱动程序时通过 NTLM 代理路由流量
- azure-devops - Azure Devops - 自托管代理上的 PowerShell 任务
- python - 如何使用 PIL 在 python 中过滤图像?