RxJS迁移5到6 - 取消订阅TakeUntil

Jur*_*uri 8 migration subscription rxjs rxjs6

在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();
  }
}
Run Code Online (Sandbox Code Playgroud)

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

this.myService.myEventEmitter.pipe(
  takeUntil(this.ngUnsubscribe))
  .subscribe(this.onDataPolling.bind(this));
Run Code Online (Sandbox Code Playgroud)

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

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

编辑:这在干净安装后确实有效,是在RxJS 6中取消订阅的最佳方式.

Par*_*rde 9

import { takeUntil } from 'rxjs/operators';

.pipe(takeUntil(this.destroyed$)).subscribe({YOUR_CODE})
Run Code Online (Sandbox Code Playgroud)

这应该有所帮助.


Tah*_*ued -3

this.ngUnsubscribe.complete();
Run Code Online (Sandbox Code Playgroud)

this.ngUnsubscribe.unsubscribe();
Run Code Online (Sandbox Code Playgroud)

  • 我认为这是不正确的。这是取消订阅的两种不同方式 https://blog.codecentric.de/en/2018/01/ Different-ways-unsubscribing-rxjs-observables-angular/ (4认同)