【发布时间】:2019-07-07 21:03:33
【问题描述】:
我正在使用角度 7 到 7 的结构指令来根据用户角色隐藏应用程序的某些部分。用户角色从 jwt 令牌中解码。但是我遇到了问题。我在 Angular 6 中使用了相同的实现并且没有任何问题,但是我尝试的任何方法似乎都不起作用。如果我以管理员身份登录,我需要刷新浏览器以显示或隐藏管理员链接(如果我以普通用户身份登录)。错误消息已在下面发布,我添加了 hasRole.directive 和 html 链接
NavComponent.html:2 错误类型错误:无法读取未定义的属性“角色” 在 HasRoleDirective.push../src/app/_directives/hasRole.directive.ts.HasRoleDirective.ngOnInit (hasRole.directive.ts:17) 在 checkAndUpdateDirectiveInline (core.js:20665) 在 checkAndUpdateNodeInline (core.js:21929) 在 checkAndUpdateNode (core.js:21891) 在 debugCheckAndUpdateNode (core.js:22525) 在 debugCheckDirectivesFn (core.js:22485) 在 Object.eval [as updateDirectives] (NavComponent.html:5) 在 Object.debugUpdateDirectives [as updateDirectives] (core.js:22477) 在 checkAndUpdateView (core.js:21873) 在 callViewAction (core.js:22114)
import { Directive, Input, ViewContainerRef, TemplateRef, OnInit } from '@angular/core';
import { AuthService } from '../_services/auth.service';
@Directive({
selector: '[appHasRole]'
})
export class HasRoleDirective implements OnInit {
@Input() appHasRole: string[];
isVisible = false;
constructor(
private viewContainerRef: ViewContainerRef,
private templateRef: TemplateRef<any>,
private authService: AuthService) { }
ngOnInit() {
const userRoles = this.authService.decodedToken.role as Array<string>;
// if no roles clear the view container ref
if (!userRoles) {
this.viewContainerRef.clear();
}
// if user has role needed then render the element
if (this.authService.roleMatch(this.appHasRole)) {
if (!this.isVisible) {
this.isVisible = true;
this.viewContainerRef.createEmbeddedView(this.templateRef);
} else {
this.isVisible = false;
this.viewContainerRef.clear();
}
}
}
}
<ul class="navbar-nav">
<li *appHasRole="['Admin', 'Moderator']" class="nav-item" routerLinkActive="active" >
<a class="nav-link" [routerLink]="['/admin']" id="side-menu">Admin</a>
</li>
【问题讨论】: