在我的Angular应用中,我设置了路由app.routing.ts
,如下所示:
const routes: Routes = [{
path: '',
redirectTo: '/login',
pathMatch: 'full',
canActivate: [LoginGuard]
},
{
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: 'customer_dashboard',
component: CustomerLayoutComponent,
canActivate: [AuthGuardService],
data: {
expectedRole: 'Customer'
},
children: [{
path: '',
loadChildren: './layouts/customer-layout/customer-layout.module#CustomerLayoutModule'
}]
},
{
path: '',
component: MobiLayoutComponent,
canActivate: [AuthGuardService],
data: {
expectedRole: 'Mobilink'
},
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 {}
这是我的登录身份验证保护器
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { LoginAuthenticateService } from './login-authenticate.service';
import * as decode from 'jwt-decode';
@Injectable()
export class LoginAuthenticateGuardService implements CanActivate {
constructor(public auth:LoginAuthenticateService,public router:Router) {
}
canActivate():boolean{
if (this.auth.isAuthenticated()) {
const token = localStorage.getItem('token');
const tokenPayload = decode(token);
const user_role=tokenPayload['role'].toString();
if(user_role=='Admin')
{
this.router.navigate(['dashboard']);
return false;
}
else if(user_role=='Customer')
{
this.router.navigate(['customer_dashboard']);
return false;
}
else if(user_role=='Mobilink')
{
this.router.navigate(['mobilink_dashboard']);
return false;
}
}
return true;
}
}
除了一个奇怪的问题,其他所有内容都工作正常,例如,当我点击网址localhost:4200
时,浏览器会将我定向到locahost:4200 / login,但这很好,但是只要我手动刷新页面localhost:4200/login
, Angular将我引向localhot:4200/login/login
,这很奇怪,每当我手动刷新页面localhost:4200 / login / login时,我什么都没得到。