如何订阅一次事件发射器?

How to subscribe to event emitter once?

// Part of service
public someEvent: EventEmitter<number> = new EventEmitter();

....

// Component
@Component({
  selector: 'some-component',
  template: `...`
})
export class SomeComponent {
  constructor(public service: Service) {
    this.service.someEvent.subscribe((x) => {
      // Do something
    });
  }
}

SomeComponent显示在/路由中。当我导航到我的应用程序中的不同路线并再次返回时,SomeComponent 将再次订阅该事件,导致回调触发两次。如何订阅一次事件或在销毁组件时取消订阅并再次订阅?

// Can't subscribe after.
ngOnDestroy() {
  this.service.someEvent.unsubscribe();
}

调用 subscribe returns 和 instance of Disposable, which has a method dispose

或者如果您使用的是 RxJS 5,dispose has been renamed to unsubscribe(感谢@EricMartinez)。

并且来自 RxJS docs

...when we're no longer interested in receiving the data as it comes streaming in, we call dispose on our subscription.


存储您对 subscribe 的调用结果,稍后在 ngOnDestroy 内处理订阅。

RxJS 5:

export class SomeComponent implements OnDestroy {
  constructor(public service: Service) {
    this.subscription = this.service.someEvent.subscribe((x) => {...});
  }
  ngOnDestroy() {
      this.subscription.unsubscribe();
  }
}

RxJS <5:

export class SomeComponent implements OnDestroy {
  constructor(public service: Service) {
    this.subscription = this.service.someEvent.subscribe((x) => {...});
  }
  ngOnDestroy() {
      this.subscription.dispose();
  }
}

你可以这样做:

import { OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Rx';

export class SomeComponent implements OnDestroy {
  private _subscription: Subscription;
  constructor(public service: Service) {
    this._subscription = this.service.someEvent.subscribe((x) => {
      // Do something
    });
  }
}

ngOnDestroy(){
  this._subscription.unsubscribe();
}