Значение, переданное в директиву, иногда не определено - PullRequest
0 голосов
/ 09 января 2020

На компоненте Angular у меня есть следующее:

export class PostAboutComponent implements OnInit {

  postId: number;

  constructor(private route: ActivatedRoute, private router: Router, private postService: PostService) { }

  ngOnInit() {

    this.route.paramMap.subscribe(parameters => {
      this.postId = parameters.has('postId') ? +parameters.get('postId') : undefined;
    })
  }
}

На компоненте HTML У меня есть:

<p *authorize="'EditPost'; id postId">
  <button (click)="editPost()">Edit post</button>
</p>

Директива авторизации следующая:

export class AuthorizeDirective implements OnInit {

  private notifier: Subscription;

  requirement: Requirement;
  id: number;

  @Input() set authorize(requirement: string) {
    this.requirement = Requirement[requirement];
  }

  @Input() set authorizeId(id: number) {
    this.id = id;
  }

  constructor(private element: ElementRef, private template: TemplateRef<any>, private container: ViewContainerRef, private renderer: Renderer2, private authorizationService: AuthorizationService) { }

  ngOnInit() { 

    console.log("id: " + this.id);

    this.authorizationService.authorize(this.requirement, this.id).pipe(
      distinctUntilChanged()
    ).subscribe(x => {
      x ? this.container.createEmbeddedView(this.template) : this.container.clear();
    });
  }
}

Случается так, что иногда id равен undefined в директиве Authorize в:

console.log("id: " + this.id);

В других случаях это не так ... И если я перефразирую sh страница никогда не бывает неопределенной.

Что мне здесь не хватает?

1 Ответ

0 голосов
/ 09 января 2020

Вам необходимо изменить HTML следующим образом для привязки к работе,

Чтобы привязать значение к идентификатору структурной директивы, используйте identifier_name: valueToBind

<p *authorize="'EditPost'; id: postId">
  <button (click)="editPost()">Edit post</button>
</p>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...