1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Angular自定义指令实现角色权限控制

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

时间:2022-02-14 13:46:40

相关推荐

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>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。