受auth Guard服务保护的多个布局路由无法正常工作

时间:2019-03-28 08:45:37

标签: angular angular4-router

在我的Angular App中,我为三个不同的用户提供了三种不同的布局admin的布局 公司的xyzlayout 客户的客户布局

我为上述所有用户设置了三个不同的模块和路由模块,然后分别将每个模块导入应用程序主模块中。一切在管理员和公司角色下都可以正常工作,但是一旦我以客户角色登录,我将面临登录后出现奇怪的问题,我被路由到customer_dashboard,这很好,但是当我导航侧栏时,系统注销了我,因为预期角色与在authguard服务类中实现的当前角色不匹配。但是,一旦我删除了我xyzlayout路由customerlayout开始正常

以下是我的  1)app.routing.module.ts代码  2)认证卫队服务文件代码  3)登录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;
}

}

-------- Login.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']);
   }

0 个答案:

没有答案