尝试根据用户在我的 Angular 应用程序中的角色加载多个模块。
一旦用户被验证并且应用程序收到一条成功消息,这就是我所做的。
const user = result.data as User;
this._authSerivce.setUser(user);
this._router.navigate([this._route.snapshot.queryParams['redirectTo'] || '/home']);
我的路线所在的文件(page-routing.module.ts):
const routes: Routes = [
{ path: '', redirectTo: '/home', pathMatch: 'full' },
{ path: 'home', loadChildren: () => import('./home/home-handler.module').then(m => m.HomeHandlerModule) },
{ path: 'forgot-password', loadChildren: () => import('./forgot-password/forgot-password.module').then(m => m.ForgotPasswordModule) },
{ path: '**', redirectTo: '/404' }
];
我正在为路径“home”(home-handler.module.ts)加载这个处理程序模块:
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { RouterModule, ROUTES, Routes } from '@angular/router';
import { AuthService } from 'app/shared/services/auth.service';
@NgModule({
declarations: [],
imports: [
CommonModule,
RouterModule
],
providers: [
{
provide: ROUTES,
useFactory: configHomeHandlerRoutes,
deps: [AuthService],
multi: true
}
]
})
export class HomeHandlerModule { }
export function configHomeHandlerRoutes(authService: AuthService) {
let routes: Routes = [];
if (authService.hasRole('Dispatcher')) {
routes = [
{
path: '', loadChildren: () => import('./dispatcher/dispatcher.module').then(mod => mod.DispatcherModule)
}
];
} else {
routes = [
{
path: '', loadChildren: () => import('./default/default.module').then(mod => mod.DefaultModule)
}
];
}
return routes;
}
正如您在上面的代码中看到的,我正在根据用户角色加载模块。
身份验证服务如下所示:
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { User } from 'app/shared/models/user.model';
import { BehaviorSubject, Observable } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class AuthService {
private currentUserSubject: BehaviorSubject<User>;
public currentUser: Observable<User>;
constructor(private http: HttpClient, private _router: Router) {
this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));
this.currentUser = this.currentUserSubject.asObservable();
}
/**
* function to store user details in local storage
* @param user user details object
*/
setUser(user: User): void {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
}
/**
* function to get current user
*/
getUser(): User {
return this.currentUserSubject.value;
}
/**
* function to check if a user has the mentioned role
* @param role name of the role
*/
hasRole(role: string): boolean {
const user = this.getUser();
return user && user.role === role ? true : false;
}
/**
* function to check if a user has the mentioned permission
* @param permission code of the permission
*/
hasPermission(permission: string): boolean {
const user = this.getUser();
return user && user.permissions.indexOf(permission) > -1 ? true : false;
}
/**
* function to remove user details from local storage
*/
logout(): void {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
this.currentUserSubject.next(null);
}
}
问题是当具有角色调度程序的用户第一次登录并尝试重定向到主页时。在 home-handler.module.ts configHomeHandlerRoutes() 方法中。authService.getUser() 返回未定义。并始终重定向到 default.module 而不是 dispatcher.module
我还尝试了以下代码从 route.config 中删除当前主路径并重新添加它。但它重定向到 404 找不到页面路径。
AuthService 中的 setUser() 方法:
setUser(user: User): void {
// store user details and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify(user));
this.currentUserSubject.next(user);
const i = this._router.config.findIndex(x => x.path === 'home');
this._router.config.splice(i, 1);
this._router.config.push(
{
path: 'home', loadChildren: () => import('../../pages/home/home-handler.module').then(mod => mod.HomeHandlerModule)
}
);
}
我该如何解决这个问题或我哪里出错了?