Search code examples
angularservicecomponentsrunning-other-programs

Code is running but I am not in that component - Angular


I set an interval in the admin component to check for new messages. but when I logged out then I noticed that the interval method is still running.

setInterval(() => {
   this.service.checkNew();
}, 300);

// Code
checkNew() {
  this.http.get(this.basic.url + 'checknew/').subscribe((res) => {
    if (res['data'].length) {
      let sound = new Audio();
      sound.src = this.basic.static += 'sounds/alert.wav';
      sound.play();
      for (let item of res['data']) {
        if (this.contacts.length) {
          this.getItem('contacts/' + item.id + '/').then((message) => {
            this.contacts.unshift(<any>message);
          });
        }
        this.messages += 1;
        this.basic.fireAlert(item['name'] + ' Send message', 4);
      }
    }
  });
}


Check network section of console in image https://i.sstatic.net/18zpu.png


Solution

  • Like with subscriptions, those callbacks aren't destroyed when you exit the compontent.

    So you need to store the reference to the interval when creating it:

    this.checkInterval = setInterval(() => {
       this.service.checkNew();
    }, 300);
    

    and add clearInterval in ngOnDestroy to destroy it when your component is destroyed:

    ngOnDestroy() {
      clearInterval(this.checkInterval);
    }