首页 > 解决方案 > 受身份验证服务保护的多个布局路线无法正常工作

问题描述

在我的 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']);
   }

标签: angularangular4-router

解决方案


推荐阅读