Angular 一条路径根据条件加载多个模块

问题描述

尝试根据用户在我的 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)
            }
        );

    }

我该如何解决这个问题或哪里出错了?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...