// 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();
}https://stackoverflow.com/questions/34839057
复制相似问题