在父级组件中,我有一个列表:
items: SomeType;
此列表从服务获取值:
this.someService.items$.subscribe(items => {
this.items = items;
});
有时,此列表将使用新条件进行更新:
this.someService.getData(this.criteria);
这很好。
还为该列表中的每个元素插入了一个子组件:
<ul *ngFor="for let item of items">
<app-list-item [item]="item"></app-list-item>
</ul>
这也很好,但是仅在父组件中第一次加载this.items
。
子组件也从服务中获取值:
ngOnInit() {
this.someOtherService.mapping$.subscribe(mapping => {
this.mapping = mapping;
});
}
ngOnDestroy() {
this.someOtherService.mapping$.unsubscribe();
}
当父组件中的条件更改并且再次加载项目列表时,子组件失败,并显示以下错误消息:
错误 消息:“对象取消订阅” 名称:“ ObjectUnsubscribedError”
当我在子组件的 this.someOtherService.mapping$.unsubscribe();
方法中删除ngOnDestroy
时,它再次起作用。但是当组件被销毁时,我不应该unsubscribe
吗?
答案 0 :(得分:2)
您取消订阅儿童的方式不正确。您正在取消可观察的订阅,而不是订阅。应该是
sosSubscription: Subscription;
ngOnInit() {
this.sosSubscription = this.someOtherService.mapping$.subscribe(mapping => {
this.mapping = mapping;
});
}
ngOnDestroy() {
this.sosSubscription.unsubscribe();
}