每次组件加载时,订阅代码都会逐步触发 [英] Subscription Code Firing off Incrementally Every Time Component Loads
问题描述
在组件的ngOnInit
中,我具有以下内容:
In my component's ngOnInit
I have the following:
public Subscription: Subscription;
ngOnInit() {
this.subscription = this.myService.currentData.subscribe( i => {
this.currentData = i;
this.function(this.currentData)
});
}
当我的组件加载时,我让它订阅了服务中的一些数据以供以后在函数中使用.第一次加载它效果很好.但是,当我加载到另一个模块然后返回时,该功能将触发两次.每次我重复此过程时,该功能都会触发并递增.这意味着如果我进出模块说5次,该功能将关闭5次.
When my component loads, I have it subscribe to some data in a service to later use in a function. Loading it the first time works great. However, when I load to another module then come back, the function will fire off two times. Every time I repeat this process the function will fire off and increment. Meaning if I switch in and out of the module say 5 times, the function will fire off 5 times.
我试图解决此问题的方法是像这样向ngOnDestroy
添加取消订阅:
My attempt at solving this was to add an unsubscribe to ngOnDestroy
like so:
ngOnDestroy() {
this.subscription.unsubscribe();
}
但是,这似乎仍然无济于事,因为问题仍然存在.
However this seems to do nothing as the issue still occurs.
推荐答案
存在两个问题.首先,我是错误地声明了我的订阅.
Two issues were present. First off, I was declaring my Subscription incorrectly.
代替此:
public Subscription: Subscription;
这是需要输入的内容:
public Subscription = new Subscription();
此外,我没有将我的订阅等同于我的订阅语句,而是切换到了.add().这使我可以将订阅对象分配给所有订阅者,然后一次性取消订阅:
Also, instead of equating my Subscription to my subscribe statement, I switched to .add(). This allows me to have my subscription object be assigned to all subscribers and unsubscribe them in one go:
this.Subscription.add(this.myService.currentData.subscribe( i => {
this.currentData = i;
this.function(this.currentData)
}));
这篇关于每次组件加载时,订阅代码都会逐步触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!