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

前端之家收集整理的这篇文章主要介绍了角度 – 如何订阅事件发射器一次?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
// 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显示在/ route中.当我在我的应用程序中导航到不同的路由,并再次返回时,SomeComponent将再次订阅该事件,导致回调触发两次.如何订阅事件一次或取消订阅销毁组件并再次订阅

// Can't subscribe after.
ngOnDestroy() {
  this.service.someEvent.unsubscribe();
}
订阅的呼叫返回 instance of Disposable,其方法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.

存储您的呼叫结果以订阅,然后在ngOnDestroy中处理订阅.

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

猜你在找的Angularjs相关文章