【问题标题】:Is any standard way to role based access file in angular?是否有任何标准方式来以角度访问基于角色的文件?
【发布时间】:2022-01-12 11:43:32
【问题描述】:

我在 Angular 中开发了 4 个角色访问项目。仪表板有不同的内容页面。每当登录门户时,最初称为仪表板页面。

此仪表板内容将根据记录的用户角色显示。我用过 ngSwitch。任何人都知道不同的实现方式,而不是使用 ngSwitch。请分享您的答案。 它有效,但我想要不同的解决方案

我已经解释了我做了什么,

定义4个角色

超级管理员、管理员、管理员用户、用户

我创建了 4 个组件文件。按照这个代码component.ts文件

  export class DashboardComponent implements OnInit {
   userRole: string;
   constructor(private authService: AuthService) {
   this.userRole = this.authService.userRole();
  }

html 文件:

  <div [ngSwitch]="userRole">
    <app-header-component title="Dashboard" *ngSwitchCase="'SuperAdmin'">
    </app-header-component>

    <app-system-integrator-dashboard *ngSwitchCase="'Admin'">                
    </app-system-integrator-dashboard>

    <app-organization-admin-dashboard *ngSwitchCase="'AdminUser'">              
    </app-organization-admin-dashboard>

    <app-organization-user-dashboard *ngSwitchCase="'User'">                
    </app-organization-user-dashboard> 
  </div>

【问题讨论】:

  • 这不是问题的答案,而是提示。请记住,在客户端上执行(或发送到)客户端的任何内容都应视为公开的。因此,使用 Angular 隐藏内容并不意味着用户无法访问它。

标签: javascript angular roles


【解决方案1】:

创建类似指令

/* Usage : *roleIsOneOf="[userType.ADMIN, userType.ANALYST, userType.SUPER_ANALYST]" */
@Directive({
    selector: '[roleIsOneOf]',
})
export class RoleIsOneOfDirective {

    constructor(private authService: AuthService,
                private templateRef: TemplateRef<any>,
                private viewContainer: ViewContainerRef) {
    }

    @Input() set roleIsOneOf(allowedRoles: Role[]) {
        const userRole: Role = this.authService.userRole();
        if (allowedRoles.includes(userRole)) {
            this.viewContainer.createEmbeddedView(this.templateRef);
        } else {
            this.viewContainer.clear();
        }
    }
}

【讨论】:

  • 创建这样的结构指令类似于我们的方法。
猜你喜欢
  • 2011-04-25
  • 1970-01-01
  • 2011-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-11
  • 2017-10-19
  • 1970-01-01
相关资源
最近更新 更多