为什么删除和新添加子组件会调用 ObjectUnsubscribedError?

Why does removing and newly adding a child component invoke an ObjectUnsubscribedError?

父组件中我有一个列表:

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();
}

父组件 中的条件发生变化并再次加载项目列表时,子组件 失败并显示此错误消息:

Error message: "object unsubscribed" name: "ObjectUnsubscribedError"

当我在 子组件的 ngOnDestroy 方法中删除 this.someOtherService.mapping$.unsubscribe(); 时,它再次工作。但是当组件被销毁时,我不应该 unsubscribe 吗?

您在 child 上退订的方式不正确。您取消订阅可观察对象,而不是订阅。应该是;

sosSubscription: Subscription;

ngOnInit() {
  this.sosSubscription = this.someOtherService.mapping$.subscribe(mapping => {
    this.mapping = mapping;
  });
}

ngOnDestroy() {
  this.sosSubscription.unsubscribe();
}