Angular自定义指令实现角色权限控制

一、创建AuthDirective

ng g d auth

 二、修改ngOnChanges方法并添加视图监听方法

purview(roles): boolean {
    const moduleName = this.router.routerState.snapshot.url.split('/')[3];
    const userRoles = this.getSession('userinfo').roles;
    let roleList =
      userRoles.find((item) => item.role === moduleName)?.list || [];
    for (let i = 0; i < roles.length; i++) {
      if (roleList.includes(roles[i])) {
        return true;
      }
    }
    return false;
  }
import {
  Directive,
  Input,
  OnChanges,
  SimpleChanges,
  TemplateRef,
  ViewContainerRef,
} from '@angular/core';
import { AuthService } from 'src/app/@core/services/auth.service';

@Directive({
  selector: '[appAuth]',
})
export class AuthDirective implements OnChanges {
  @Input('appAuth') roles: string[] = [];
  hasView = false;
  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef,
    private authService: AuthService
  ) {}

  ngOnChanges(changes: SimpleChanges): void {
    if (this.authService.purview(this.roles)) {
      this.createView();
    } else {
      this.viewContainer.clear();
      this.hasView = false;
    }
  }

  // 创建视图
  private createView(): void {
    this.viewContainer.createEmbeddedView(this.templateRef);
    this.hasView = true;
  }
}

三、模块内引入指令并在组件内使用

1. 对应的Module内引入import { AuthDirective } from './directive/auth.directive';并在declarations和export(外模块需要使用的话)中添加

2.在角色控制的组件内传入角色限制条件(传入的条件为对应的角色所包含的操作权限,我的系统内区分为all/edit/readonly)

<app-module-owner-change
                    *appAuth="['all']"
                    [module]="'auto-test'"
                  ></app-module-owner-change>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值