我有一项具有此功能的服务
getCurrentUserPermissions() {
return JSON.parse(localStorage.getItem('currentUserPermissions'));
}
现在我创建一个指令来显示和隐藏菜单
*hasPermissions="['stations','users']"
指示
import {Directive, Input, TemplateRef, ViewContainerRef} from '@angular/core';
import {SiteService} from "../services/site.service";
@Directive({selector: '[hasPermissions]'})
export class HasPermissionsDirective {
@Input("hasPermissions") conditions: string[];
constructor(private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef,
private siteService: SiteService
) {
}
ngOnInit() {
let BreakException = {};
let result: boolean = true;
let currentUserPermissions = this.siteService.getCurrentUserPermissions();
try {
this.conditions.forEach(function (keyCondition) {
if (currentUserPermissions[keyCondition] !== true) {
result = false;
throw BreakException;
}
});
} catch (e) {
if (e !== BreakException) throw e;
}
if (result) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
}
如何查看 this.siteService.getCurrentUserPermissions() 的更改?因为现在我必须刷新页面才能重新渲染指令才能工作,如果我更改权限