【发布时间】:2019-11-24 11:48:34
【问题描述】:
我有一个小问题,我需要在我的 Angular 应用程序中应用角色验证。 该应用程序是从每个页面包含许多组件的页面构建的。 用户权限是在组件级别授予的,所以遗憾的是我不能只使用路由保护来授予整个页面,我必须使用简单的 *ngIf 为每个组件添加验证:
<results-component
*ngIf="auth.hasPermission('driver_productivity')"
[format] = "driver_productivityFormat"
[IsFullWidth] = "IsFullWidth"
(customEvent)="showPrint($event)">
</results-component>
auth.service.ts:
hasPermission(permissionName){
if (!this.tokenPayload){
this.getToken().subscribe(t=>{this.tokenPayload=decode(t.getValue())});
if (this.tokenPayload.roles && this.tokenPayload.roles.length>0 ){
this.permissions={};
for (let i=0;i<this.tokenPayload.roles.length;i++){
this.permissions[this.tokenPayload.roles[i]]=true
}
}
}
return this.permissions[permissionName]
}
但由于我每页有多个组件,因此此验证累积的时间太多,因此它成为了一个滥用的解决方案。
[Violation] 'setInterval' 处理程序耗时 150 毫秒 zone.js:1755 [Violation] “点击”处理程序耗时 318 毫秒 zone.js:2279 [违规] 'requestAnimationFrame' 处理程序耗时 84 毫秒 zone.js:1755 [违规] “点击”处理程序耗时 261 毫秒
有没有办法让 *ngIf 只运行一次?首次加载组件时?
【问题讨论】:
-
我们通过创建自己的指令完成了类似的事情——例如添加/隐藏导航元素、按钮和其他功能。用户信息和角色在登录时加载并存储在全局服务类中。指令输入接受用户的角色和允许访问 UI 元素的角色列表。该指令与 ngif 没有什么不同——它基于元素创建或销毁。
标签: angular typescript permissions