【问题标题】:RxJS Migration 5 to 6 - Unsubscribe with TakeUntilRxJS 迁移 5 到 6 - 使用 TakeUntil 取消订阅
【发布时间】:2018-11-09 10:28:02
【问题描述】:

在 RxJS 6 中取消订阅的最佳方式是什么?

我的“旧”RxJS 5 代码如下所示

export class MyComponent implements OnInit, OnDestroy {
  private ngUnsubscribe: Subject<any> = new Subject();

  this.myService.myEventEmitter
    .takeUntil(this.ngUnsubscribe)
    .subscribe(this.onDataPolling.bind(this));

  public ngOnDestroy(): void {
    this.ngUnsubscribe.next();
    this.ngUnsubscribe.complete();
  }
}

在迁移到 RxJS 6 时,我运行 rxjs-5-to-6-migrate 并得到了

this.myService.myEventEmitter.pipe(
  takeUntil(this.ngUnsubscribe))
  .subscribe(this.onDataPolling.bind(this));

但这不起作用,因为 EventEmitter 没有管道方法。

在 RxJS 6 中取消订阅的最佳方式是什么?

编辑:这在全新安装后确实有效,并且是在 RxJS 6 中取消订阅的最佳方式。

【问题讨论】:

  • 这不是真的。 EventEmitter 扩展 Subject 扩展 Observable 所以它确实有 pipe() 方法。问题将出在其他地方。
  • 你在我的服务中我正在使用 import { EventEmitter } from "@angular/core"。但是迁移这个的最好方法是什么???
  • 但是它有什么问题呢? myEventEmitter.pipe(...) 是正确的,所以它不起作用或无法编译或什么?
  • 无法编译
  • 你能分享一下它抛出了什么错误或者这是一个秘密吗?

标签: migration rxjs subscription rxjs6


【解决方案1】:
import { takeUntil } from 'rxjs/operators';

.pipe(takeUntil(this.destroyed$)).subscribe({YOUR_CODE})

这应该会有所帮助。

【讨论】:

    【解决方案2】:
    this.ngUnsubscribe.complete();
    

    this.ngUnsubscribe.unsubscribe();
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-24
    • 2017-04-10
    • 1970-01-01
    • 2018-08-20
    • 2016-12-20
    • 2018-11-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多