30
// 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();
}
4

2 回答 2

38

调用subscribe返回一个实例Disposable,它有一个方法dispose

或者,如果您使用的是 RxJS 5,dispose则已重命名为unsubscribe(感谢 @EricMartinez)。

并且来自RxJS 文档

...当我们不再对接收流入的数据感兴趣时,我们在订阅上调用 dispose。


将调用结果存储subscribengOnDestroy.

RXJS 5:

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

RxJS <5:

export class SomeComponent {
  constructor (public service: Service) {
    this.subscription = this.service.someEvent.subscribe((x) => {...});
  }
  ngOnDestroy () {
      this.subscription.dispose();
  }
}
于 2016-01-17T14:17:27.413 回答
4

你可以这样做:

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();
}
于 2016-09-27T23:06:50.373 回答