// 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();
}
答案 0 :(得分:34)
致电subscribe
会返回instance of Disposable
,其方法为dispose
。
或者如果您使用的是RxJS 5,dispose
has been renamed to unsubscribe
(感谢@EricMartinez)。
来自RxJS docs:
...当我们不再有兴趣接收数据时,我们会在订阅时调用dispose。
将您的通话结果存储到subscribe
,然后在ngOnDestroy
内处理订阅。
RxJS 5:
export class SomeComponent {
constructor (public service: Service) {
this.subscription = this.service.someEvent.subscribe((x) => {...});
}
ngOnDestroy () {
this.subscription.unsubscribe();
}
}
RxJS&lt; 5:
export class SomeComponent {
constructor (public service: Service) {
this.subscription = this.service.someEvent.subscribe((x) => {...});
}
ngOnDestroy () {
this.subscription.dispose();
}
}
答案 1 :(得分:3)
您可以这样做:
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();
}