一、创建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>