问题
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();
}
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.
回答1:
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);
}
来源:https://stackoverflow.com/questions/45363275/angular-data-callback-never-stops-even-when-unsubscribe-function-is-used