【问题标题】:how to keep only one parameter in a subject?如何在主题中只保留一个参数?
【发布时间】:2017-12-13 13:39:15
【问题描述】:

我从控制器向主题输入参数

  selectImport(event){
      this.importacionService.onChildSelectImportChanged.next(event);
  }

从我的组件importacion.component.ts 我订阅了这个主题

this.importacionService.onSelectImportChanged.subscribe( addImport => {

    this.importacionService.addImport(this.month, addImport);
   });


  }

现在一切都很好,但是当我关闭 importacion.component.ts 的对话框并再次执行此操作时,主题会创建第二个 suscbripcion 并因此创建 2 个观察者,然后当我使用 .next() 输入新数据时订阅者运行两次。

我怎样才能控制这种行为, 我的预期行为是仅在我的主题中存在和参数,并且仅在其值更改时运行

【问题讨论】:

  • 您只需要在关闭对话框时取消订阅
  • 我收到一条错误消息“对象已取消订阅”

标签: angular rxjs reactive-programming subject-observer


【解决方案1】:

把它放在你的组件中

private subscription: Subscription;

ngOnInit() {
    this.subscription = this.importacionService.onSelectImportChanged.subscribe(...);
}

ngOnDestroy() {
    if (this.subscription){
        this.subscription.unsubscribe();
    }
}

您需要取消订阅您自己创建或管理的 observables

【讨论】:

  • 我试过这样,但是当我再次打开对话框时,它会产生错误
  • 看这个:toddmotto.com/passing-data-angular-2-components-input 尝试使用输入和输出在组件之间传递数据
  • 我收到一条错误消息“对象已取消订阅”
  • 对于其他想知道您如何获得“对象取消订阅”错误的人:您可以通过在主题上调用取消订阅而不是从 .subscribe 返回的订阅来获得它。
  • @LuisRuizFigueroa 将代码示例更新为取消订阅而不是主题。
猜你喜欢
  • 2021-01-28
  • 2023-03-22
  • 2017-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多