angular - How to replace setInterval?

Asked

Viewed 259 times

1

I am currently doing a project and I need to get information from the bank that is updated and for this I am giving a get every 5 seconds using setInterval. But I know this isn’t the best of worlds, so I’d like to know what to do.

I’ve heard about Subscription or something, but I have no idea how to implement.

import { ApiService } from 'src/app/core/services/api.service';

 ngOnInit() {
    this.getFiles();
    this.interval = setInterval(() => {
      this.getFiles();
    }, 5000);
  }
  
  
  getFiles() {
    const files = this.apiService.getFiles().subscribe(data => {
        return data['response'];
    }, error => {
      console.log(error);
    });
  }

1 answer

1


You can change the setInterval() of Vanilla by Observable.timer with Angular, simply import the libs necessary and use it, can see an example working here, in the example is used tbm the method takeWhile(() => this.alive) that executes the timer only with the component concerned active, in case you don’t even need a function to perform the Http request, you can already include it with the methods:

import { ApiService } from 'src/app/core/services/api.service';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/takeWhile';
import 'rxjs/add/observable/timer';

ngOnInit() {
  Observable.timer(0,5000)  // Seta o timer para cada 5 segundos
  .takeWhile(() => this.alive) // Apenas com o componente ativo
  .subscribe(() => {
    const files = this.apiService.getFiles().subscribe(data => {
      return data['response'];
    }, error => {
    console.log(error);
    });
  });
}
  • But you can not update only if there is change? Because this way it will continue to request every 5s neh?

  • But update that, not made clear in the question??

  • You’re right. But the update is related to the value of the files variable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.