Я использую структурную директиву под углом от 7 до 7, чтобы скрыть части приложения в зависимости от роли пользователя.роль пользователя декодируется из токена jwt.Однако я сталкиваюсь с проблемами.Я использовал ту же реализацию с Angular 6, и у меня не было проблем, но все, что я пробовал, похоже, не работает.если я захожу как администратор, мне нужно обновить браузер, чтобы ссылка администратора отображалась или была скрыта, если я захожу как обычный пользователь.сообщение об ошибке было опубликовано ниже, и я добавил hasRole.directive и ссылку html
NavComponent.html: 2 ОШИБКА TypeError: Невозможно прочитать свойство 'role' undefined в HasRoleDirective.push ../ src /app / _directives / hasRole.directive.ts.HasRoleDirective.ngOnInit (hasRole.directive.ts: 17) в checkAndUpdateDirectiveInline (core.js: 20665) в checkAndUpdateNodeInline (core.js: 21929) в checkAndUdAdUpdebugCheckAndUpdateNode (core.js: 22525) в debugCheckDirectivesFn (core.js: 22485) в Object.eval [в качестве updateDirectives] (NavComponent.html: 5) в Object.debugUpdateDirectives [в качестве updateDirectives]: в качестве updateDirectives для проверки подлинности (в качестве элемента updateUp4) для проверки подлинности 22-го уровня в качестве объекта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>