Angular:即使使用取消订阅功能,数据回调也不会停止 [英] Angular: Data callback never stops even when unsubscribe function is used
问题描述
我正在尝试使用此函数更新api中的数据
I am trying to update the data from the api using this function
ngOnInit(){
setInterval(()=>{
this.getPhonebook();
}, 1000);
}
getPhonebook() {
this.showPhonebook = this.beaconProvider.getPhoneBookDirectories().subscribe(data => {
this.infos = data;
}, (err) =>{
console.log(err);
})
}
并尝试使用此方法销毁它:
and trying to destroy it using this:
ionViewDidLeave(){
this.showPhonebook.unsubscribe();
}
ngOnDestroy(){
this.showPhonebook.unsubscribe();
}
问题是当我尝试使用 ngDestroy进行销毁时
或将其附加到 IonViewDidLeave()
即使我已经在另一个页面上,该函数仍会调用该生命周期。那么有没有办法实现自动更新我渴望有角度,因为我担心给定一个大事务 setInterval
将导致错误。
The Problem is when i try to destroy using ngDestroy
or attach it to IonViewDidLeave()
lifecycle the function still calls even when I'm already on a different page. So is there a way to achieve the auto update I desire angularly since my concern that given a large transaction the setInterval
will cause errors.
推荐答案
如果在组件中使用setInterval,则需要设置clearInterval。
If you use setInterval in your component you will need to set clearInterval.
myInterval: any;
ngOnInit(){
this.myInterval = setInterval(()=>{
this.getPhonebook();
}, 1000);
}
ngOnDestroy(){
clearInterval(this.myInterval);
}
这篇关于Angular:即使使用取消订阅功能,数据回调也不会停止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!