我正在编写一个简单的组件,它将 Id 作为输入并调用服务方法来返回要显示的实体:
@Input() id: string;
ngOnInit(): void {
if (this.id != undefined && this.id != "") {
this.detailSubscription=this.service.load(this.id)
.subscribe(result => {
this.detail$ = result;
this.cd.detectChanges();
});
}
}
ngOnDestroy() {
this.cd.detach();
this.detailSubscription.unsubscribe();
}
此组件仅在第一次时有效。如果输入 Id 更改,则不会更新 View 。
我还尝试将服务调用放在 onChanges
方法中,但由于取消订阅仅在 onDestroy
方法上调用一次,因此它不起作用。
如何实现这一目标?
最佳答案
您需要使用 ngOnChanges
而不是 ngOnInit
,如下所示。 ngOnInit
只会触发一次,而 ngOnChanges
将在每次输入值更改时触发。
并在调用服务之前尝试取消订阅。
ngOnChanges(changes: SimpleChanges) {
if (changes['id']) {
if(this.detailSubscription) {
this.detailSubscription.unsubscribe();
}
//call your service here
}
}
关于angular - 在输入更改和更新 View 时调用服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44414974/