Директива Angular не работает, директива не изменяет отображение элемента - PullRequest
0 голосов
/ 10 марта 2020

Я проверил документацию и помощь онлайн, но ничего не работает. Поскольку я не могу использовать console.log из директивы (извините за новизну), я не знаю, как его протестировать или проверить, работает ли он правильно.

Мое намерение - показать / скрыть элементы в зависимости от роли пользователя. Я передаю, какие роли разрешены для каждого элемента. Затем он проверяет в директиве, совпадает ли роль текущего пользователя с любой из переданных ролей.

<div IfRole="office,shop">hi</div> //In the directive, it should transform this string into an array of roles
import { AfterContentInit, Directive, ElementRef, Input } from "@angular/core";
import { AuthService } from "../services/auth.service";
import { OnInit, TemplateRef, ViewContainerRef } from "@angular/core";
import { UserI } from "../models/user";
import { IfStmt } from "@angular/compiler";
import { type } from "os";

@Directive({
  selector: "[IfRole]"
})
export class ElementsRoleDirective {
   UserRoles: string[];
  User: UserI;

  @Input() set IfRole(roles:  string) {
     this.UserRoles = roles.split(",");
  }

  public constructor(
    private el: ElementRef,
    private templateRef: TemplateRef<any>,
    private AuthService: AuthService,
    private viewContainer: ViewContainerRef
  ) {

    this.AuthService.currentUser.subscribe(data => {
      this.User = data;
    });
    if (!this.UserRoles.includes(this.User.role))
    this.viewContainer.clear();
    else {
      this.viewContainer.createEmbeddedView(this.templateRef);
    }
  }
  ngOnInit() {}
}

1 Ответ

0 голосов
/ 10 марта 2020

попробуйте это

 this.AuthService.currentUser.subscribe(data => {
      this.User = data;

      if (!this.UserRoles.includes(this.User.role))
        this.viewContainer.clear();
      else {
       this.viewContainer.createEmbeddedView(this.templateRef);
      }
 });

Я поместил асин c код внутри обратного вызова, и теперь он должен быть обработан в нужный момент

...