I have a service that will make a call to my rest service every 2 minutes. On my service I have the following function
getNotifications(token: string) {
const body = 'xxxxxxxxx=' + token;
return this.http.post('/rest/ssss/ddddddd/notificationcount', body, this.options)
.map((res) => res.json());
}
On my component I call my service function to call the API.
this.notificationService.getNotifications(this.token).subscribe((data) => {
console.log(data);
});
I want to make this call every 2 minutes, what is the best way to do this?
If you are using rxJs 6+, you can simlpy use interval method to do. like this -
Update After comment
If you don't want to make an http call and simply want to do something after 2 minutes, then you can do something like below.
There is one more important thing you would like to do, You shoud destroy this observable once you leave your current page, because you don't want the extra computation going on behind the scene when these are not actually needed.
There are multiple options to unsubscribe from this observable.
You should save the reference to the observable and unsubscribe from it in
onDestroy
method.OR use ngx-take-until-destroy
Since you are already using
Observables
, simply make full use of it :)Obersvable.interval()
is your good friend here:In your component, do this:
Explanation:
.interval()
creates an observable that emits an event every 2 minutes..timeInterval()
convert an Observable that emits items into one that emits indications of the amount of time elapsed between those emissions..flatMap()
then wraps your each and every of service call, transform the results into an observable and return it. This ensure that the your service call at 0th, 2nd, 4th, 6th....minute is called synchronously. (think of there is a lot of.then()
), i.e, service at 2nd minute will only be called on after the 0th minute's call, and 4th will only after 2nd, and so on..subscribe()
finally you can subscribe to the dataUpdate:
If you are using pipeable operators (rxjs5 and above), simply pipe the operators instead of chaining them: