繁体   English   中英

Angular RXJS Observables - ObjectUnsubscribedError

[英]Angular RXJS Observables - ObjectUnsubscribedError

使用 Angular 我是 RXJS 可观察对象的新手,并试图解决这个错误。 我有以下基本代码:

export class EventService {

  test$ = new Subject();
  watch() {
   return this.test$;
  }
  push() {
   this.test$.next('Hello World');
  }
}

export class Component {
  watch() {
    this.eventService.watch().subscribe((obj)=>{ console.log('Helo', obj)});
  }
  test() {
    this.eventService.push();
  }
  unsubscribe(){
    this.eventService.watch().unsubscribe();
  }
}

总之,我有一个名为 test$ 的带有 rxjs 主题的事件服务。 在我的组件中,我有三个功能手表、测试、取消订阅。 所有这些都连接到 html 模板中的按钮。

我在订阅主题的组件“watch()”中运行。 然后我运行'test()',它在控制台中打印'Hello World'。 然后我运行 unsubscribe() 我假设取消订阅 test$。

问题是当我再次运行 test() 时出现错误“ObjectUnsubscribedError”。 这是什么原因以及解决方法? 我认为这与我取消订阅 test$ 的方式有关?

非常感谢提前。

这不是你退订的方式。 您可以通过在subscribe()返回的 Subscription 上调用unsubscribe()来取消订阅:

export class Component {

  private subscription: Subscription;

  watch() {
    this.subscription = this.eventService.watch().subscribe((obj)=>{ console.log('Helo', obj)});
  }
  test() {
    this.eventService.push();
  }
  unsubscribe() {
    if (this.subscription) {
      this.subscription.unsubscribe();
    }
  }
}

这是你的演示

Subject.unsubscribe()方法没有文档,因此很难解释它的作用以及它为什么存在,不幸的是。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM