gpt4 book ai didi

angular - 如何订阅一次事件发射器?

转载 作者:太空狗 更新时间:2023-10-29 16:50:36 25 4
gpt4 key购买 nike

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

最佳答案

调用 subscribe 返回 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.


存储调用 subscribe 的结果,稍后在 ngOnDestroy 中处理订阅。

RxJS 5:

export class SomeComponent implements OnDestroy {
constructor(public service: Service) {
this.subscription = this.service.someEvent.subscribe((x) => {...});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}

RxJS <5:

export class SomeComponent implements OnDestroy {
constructor(public service: Service) {
this.subscription = this.service.someEvent.subscribe((x) => {...});
}
ngOnDestroy() {
this.subscription.dispose();
}
}

关于angular - 如何订阅一次事件发射器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34839057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com