【问题标题】:Angular RXJS Observables - ObjectUnsubscribedErrorAngular RXJS Observables - ObjectUnsubscribedError
【发布时间】:2020-02-10 02:24:49
【问题描述】:

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

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

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

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

非常感谢提前。

【问题讨论】:

    标签: angular rxjs


    【解决方案1】:

    这不是您退订的方式。您可以通过在 subscribe() 返回的订阅上调用 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();
        }
      }
    }
    

    这里是your demo。

    方法Subject.unsubscribe() 没有文档,因此很难解释它的作用和存在的原因,很遗憾。

    【讨论】:

      猜你喜欢
      • 2020-02-02
      • 2016-06-05
      • 2017-03-20
      • 1970-01-01
      • 1970-01-01
      • 2016-09-07
      • 2018-11-24
      • 2018-05-11
      • 2017-10-29
      相关资源
      最近更新 更多