【发布时间】:2020-01-09 21:01:30
【问题描述】:
在 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 在 Authorize 指令中是 undefined:
console.log("id: " + this.id);
其他时候不是......如果我刷新页面永远不会不确定。
我在这里错过了什么?
【问题讨论】:
-
您在组件中异步检索 id,因此当您的指令被创建并且它的
ngOnInit运行时,它可能还没有被检索到。您可以使用this.letterSource此处 stackoverflow.com/a/59217375/9423231 之类的主题,或将您的逻辑移动到此处 angular.io/guide/structural-directives#the-appunless-property 之类的设置器中(将console.log添加到@Input() set authorizeId以查看 id 设置两次)或将逻辑移动到ngOnChanges()