Angular 应用程序中不同角色的不同仪表板视图

Different dashbard views for different roles in Angular application

我的应用程序目前有 6 个用户角色,将来可能会增加,并且对于每个用户角色,我都有不同的仪表板视图。

目前,我通过在登录时识别用户角色然后根据该用户角色更改仪表板视图来处理这种情况(同时为每个角色保持相同的路由,例如“/dashboard”)。

我这样做是因为变化不大,我只需要隐藏一些部分是一个角色并添加其他角色。 现在,由于复杂性在增加,在单个打字稿文件中处理所有仪表板视图变得越来越棘手。

我应该为所有角色制定不同的路线,还是您会建议任何不同的方法来更有效地处理这种情况?

您可以使用 dynamic component loader.

dashboard.component.ts 添加一些代码行供参考:

@Component({
    selector: 'dashboard',
    template: `
        <ng-template dashboardHost></ng-template>
    `
})
export class DashboardComponent {

    private _dashboard: DashboardItem;

    get dashboard(): DashboardItem {
        return this._dashboard;
    }
    @Input()
    set dashboard(dashboard:DashboardItem){
        if(this._dashboard != dashboard) {
            this._dashboard = dashboard;
            this.loadDashboard();
        }
    }

    @ViewChild(DashboardDirective) dashboardHost: DashboardDirective;

    constructor(private componentFactoryResolver: ComponentFactoryResolver) {
    }

    loadDashboard() {
        const dashboardItem = this.dashboard;

        const componentFactory = this.componentFactoryResolver.resolveComponentFactory(dashboardItem.component);

        const viewContainerRef = this.dashboardHost.viewContainerRef;
        viewContainerRef.clear();
        viewContainerRef.createComponent(componentFactory);
    }
}

仪表板-item.ts

import {Type} from '@angular/core';

export class DashboardItem {
  constructor(public component: Type<any>, public data: any) {}
}

dashboard.directive.ts 创建指令为:

import {Directive, ViewContainerRef} from '@angular/core';

@Directive({selector: '[dashboardHost]'})
export class DashboardDirective {
  constructor(public viewContainerRef: ViewContainerRef) { }
}

用途:

<dashboard [dashboard]="Dashboard"></dashboard>

get Dashboard() {
    // add your logic here
}