Angular: Data callback never stops even when unsubscribe function is used

梦想的初衷 提交于 2019-12-24 08:01:22

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!