You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular的[role]指令中使用双角色实现权限控制

让Angular的app-authorize-view组件支持多角色验证

要让这个授权组件支持传入多个角色并验证,你可以按以下步骤修改代码:

1. 更新组件的TS逻辑

把单角色输入改成字符串数组,同时调整权限判断逻辑,检查用户角色是否在允许的角色列表中:

import { Component, OnInit, Input } from '@angular/core';
import { SecurityService } from './your-security-service-path'; // 替换为实际路径

export class AuthorizeViewComponent implements OnInit {
  constructor(private securityService: SecurityService) { }

  ngOnInit(): void {
  }

  // 改为字符串数组,支持多角色传入
  @Input()
  roles: string[] = [];

  public isAuthorized(): boolean {
    if (this.roles.length > 0) {
      const userRole = this.securityService.getRole();
      // 判断用户角色是否在允许的列表内
      return this.roles.includes(userRole);
    } else {
      // 未传角色时,仅验证用户是否已登录
      return this.securityService.isAuthenticated();
    }
  }
}

2. 组件模板保持不变

原有的内容投影逻辑无需修改,继续保留:

<ng-content *ngIf="!isAuthorized()" select="[notAuthorized]"></ng-content>
<ng-content *ngIf="isAuthorized()" select="[Authorized]"></ng-content>

3. 父组件传入多角色

现在可以直接传入多个角色数组,比如同时允许Admin和Manager角色访问:

<app-authorize-view [roles]="['Admin', 'Manager']">
  <ng-container Authorized>
    <a [routerLink]="['/DemandeConges', row.id]">
      <button mat-icon-button>
        <mat-icon color="secondary">visibility</mat-icon>
      </button>
    </a>
  </ng-container>
  <!-- 可选:添加未授权时的提示内容 -->
  <ng-container notAuthorized>
    <span>无权限查看此内容</span>
  </ng-container>
</app-authorize-view>

额外优化:兼容旧单角色写法(可选)

如果需要保留原来单角色的传入方式(比如[role]="'Admin'"),可以添加setter做兼容处理:

@Input()
set role(role: string) {
  if (role) {
    this.roles = [role];
  }
}

@Input()
roles: string[] = [];

这样旧的单角色写法依然有效,同时支持新的多角色数组传入。


内容的提问来源于stack exchange,提问作者salah kimi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 22:40:30