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