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

Time:06-29

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.stack.imgur.com/18zpu.png

CodePudding user response:

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);
}

CodePudding user response:

Using setInterval for polling is a very bad idea. setInterval doesn't care about the previous call, if for some reason your server slows down you will end up enqueuing requests until your server crashes. instead of that i recommend you using RxJs

const fakeAsyncWork = (index) => of(index).pipe(delay(10 * index))
let index = 1;
defer(() => fakeAsyncWork(index))
  .pipe(repeatWhen((res) => res.pipe(delay(100))))
  .subscribe((res) => {
    console.log(res   ' fake async took: '   10 * index   'ms to perform');
    index = index   5;
  }); 

This way you can ensure, that a delay will be respected between each call. To release the subscription you can call to unsubscribe on the ngOnDestroy or use this library https://github.com/ngneat/until-destroy

  • Related