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