Reputation: 3038
I want to call an Observable
method (which is calling and external API) every 5 minutes in angular .ts
file.
For example, I have a method like this:
updateMasterTokenAsync(): Observable<boolean> {
const httpHeaders = new HttpHeaders();
httpHeaders.append('Content-Type', 'application/json');
return this.http.post<any>(
this.API_URL + this.API_ENDPOINT_LOGIN,
{'username': 'test', 'password': 'test'},
{headers: httpHeaders}
).pipe(
tap(res => localStorage.setItem('accessToken', res['token'])),
map(
res => true,
error => false
)
);
}
I want this method to be called each 5 minutes. I used setInterval
solution, But it's not working properly. It will call my method but the http.post
section is not working well. Can anybody help me?
thanks in advance
Upvotes: 0
Views: 449
Reputation: 29325
you need to subscribe to observables for them to work, and there's no need to use setInterval here since rxjs comes with an invterval and timer observable..
timer(0, 300000).pipe(
switchMapTo(this.updateMasterTokenAsync())
).subscribe(
result => console.log(result),
err => console.log(err)
)
just unsubscribe from this whenever you're destroying the component or service.
this will start right away, if you want the first call to wait 5 minutes, then use interval()
Upvotes: 4