我正在尝试创建一个简单的伪指令*appIfProjectPermission="'view_project_info'"
,如果用户具有view_project_info
的权限,该伪指令将显示页面的各个部分。有些部分很复杂,为了减轻应用程序的负担,我希望删除它,而不是简单地display: hidden;
。
我遇到的问题是权限来自可观察对象,并且我必须向可观察对象发出信号以影响指令。知道我该如何处理吗?
我的代码可以在下面找到:
import { Directive, Input, TemplateRef, ViewContainerRef, OnInit } from '@angular/core';
import { PermissionService, Permission } from '../services/permission.service';
@Directive({
selector: '[appIfProjectPermission]'
})
export class IfProjectPermissionDirective implements OnInit {
private hasView = false;
private permissions$;
private permissions: Array<Permission['identifier']> = [];
constructor(
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private permissionService: PermissionService
) {}
ngOnInit() {
this.permissions$ = this.permissionService.permissions$
.subscribe((permissions: Permission[]) => {
for (let permission of permissions) {
this.permissions.push(permission.identifier);
}
});
}
ngOnDestroy() {
this.permissions$.unsubscribe();
}
@Input() set appIfProjectPermission(identifier: string) {
if ((this.permissions.includes(identifier)) && (!this.hasView)) {
this.viewContainer.createEmbeddedView(this.templateRef);
this.hasView = true;
} else if ((this.permissions.includes(identifier)) && (this.hasView)) {
this.viewContainer.clear();
this.hasView = false;
}
}
}
答案 0 :(得分:0)
最好将授权逻辑保留在权限服务中。这不仅有益于分离关注点,还使您免于推送权限更改。
@Input() set appIfProjectPermission(identifier: string) {
if ((this.permissionService.isAuthorized(identifier)) && (!this.hasView)) {
this.viewContainer.createEmbeddedView(this.templateRef);
this.hasView = true;
} else if ((this.permissions.includes(identifier)) && (this.hasView)) {
this.viewContainer.clear();
this.hasView = false;
}
}