在现实业务系统中,为了保证业务数据安全,要求不同的人员登录后页面现实不同的按钮,根据单前人员所拥有的角色以及权限点进行现实或隐藏。在Angular中可以利用自定义指令来快速实现
actPermissionDirective.ts
tsimport { Directive, ElementRef, Input, OnChanges, OnInit, SimpleChanges, TemplateRef, ViewContainerRef } from "@angular/core";
import { ActService } from "@app/services/act.service";
@Directive({
selector: '[aas]',
exportAs: 'aas',
})
export class actPermissionDirective implements OnChanges{
@Input('role')
role:string[] = []
@Input('act')
act:string[] = []
//hasView = false
constructor(private el:ElementRef<any>,private actService:ActService){
}
ngOnChanges(changes: SimpleChanges): void {
if(!this.actService.hasPermission(this.role,this.act)){
console.log("没有权限");
this.el.nativeElement.style = "display:none !important"
}
}
}
ActService.ts
tsimport { Injectable } from '@angular/core';
type PermissionType = {
roles?: string[]
acts?: string[]
}
@Injectable({
providedIn: 'root'
})
export class ActService {
/** 角色组 */
private roles:string[] = []
/** 权限点组 */
private acts:string[] = []
constructor(){
}
set permission(data:PermissionType){
if(data.roles){
this.roles = data.roles
}
if(data.acts){
this.acts = data.acts
}
}
hasPermission(roleList:string[] = [],actList:string[] = []){
if(roleList.length == 0 && actList.length == 0){
return true
}
// TODO 根据角色和权限点 自定义逻辑
if(roleList.length > 0){
const superAdmin = "admin"
return this.roles.some(role => {
return superAdmin === role || roleList.includes(role)
})
}
if(actList.length > 0){
const allAct = "*:*:*"
return this.acts.some(act => {
return allAct === act || actList.includes(act)
})
}
return true
}
}
用户登录后需要将用户的角色和权限set 保存
页面使用案例
html<button (click)="viewRowData(tableData)" >查看</button>
<button (click)="editRowData(tableData)" aas [role]="['role']">编辑</button>


本文作者:千寻
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!