所以,我在一个路由项目中遇到了问题。我按照这个步骤。
- 登录系统时,我将令牌和用户名保存在本地存储中。
- 登录成功,打开仪表板页面。
- 我关闭浏览器并再次打开项目。登录页面中的页面路由,仪表板页面中没有,只有当我输入正确的 url 页面路由时才可以。所以数据在本地存储中。在这部分中,我想在仪表板页面中路由页面,而不是在登录时,只有当我在本地存储中有数据用户时。如果本地存储为空,我想在登录页面中路由
我有这个路由:
const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'forgotpassword', component: ForgotPasswordComponent },
{ path: '', component: LoginComponent },
{ path: 'panel', canActivate: [AuthGuard], loadChildren: () => import('./panel/panel.module').then(m => m.PanelModule) }
];
还有这个路由面板。
const routes: Routes = [
{
path: '',
component: PanelComponent,
canActivate: [AuthGuard],
canActivateChild: [AuthGuard],
children: [
{
path: '',
pathMatch: 'full',
redirectTo: 'dashboard'
},
{
path: 'dashboard',
component: DashboardComponent,
data: { allowedRoles: [Role.COMMUNITY_ADMIN] }
},
.....
{
path: 'documents',
component: DocumentComponent,
data: { allowedRoles: [Role.CHAIRMAN] }
},
]
}
];
我有这个 Authguard。
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (this.authService.currentUserLogged){
return true;
}
this.router.navigateByUrl('/');
return false;
}
canActivateChild(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (this.authService.currentUserLogged) {
const userRoles = currentUserLogged.user?.user_roles;
const allowedRoles = route.data.allowedRoles;
return this.authService.isAuthorized(allowedRoles, userRoles);
}
this.router.navigateByUrl('/');
return false;
}
更新
authservice.ts
currentUserLogged!: IUserLoggedInAccountDTO;
constructor(protected httpClient: HttpClient, private router: Router) {
this.currentUserLogged = this.getUserLoggedInAccount();
}
private getUserLoggedInAccount = (): IUserLoggedInAccountDTO => (JSON.parse(localStorage.getItem(environment.userLoggedInAccountLocalStorageKey) || '{}'));
isAuthorized(allowedRoles: any, userRoles: any): boolean {
if (allowedRoles === null || allowedRoles?.length === 0) {
return true;
}
if (userRoles !== null && userRoles?.length !== 0) {
const userRolesFiltered = userRoles.filter((userRole: any) => formatDate(userRole.end_date, 'yyyy-MM-dd', 'en_US') >= formatDate(new Date(), 'yyyy-MM-dd', 'en_US'));
const authorise: boolean = userRolesFiltered.some((userRole: any) => allowedRoles.includes(userRole.role.name));
if (!authorise) {
this.router.navigate(['/']);
return false;
}
return true;
}
return false;
}
非常感谢您的回答!