Reputation: 3450
I'm executing some requests in loop for the same API. On server-side I need to check the previous result to make some changes. But I can't see the previous result if requests are more than one in loop.
in component:
this.service.createEmail(...).delay(5000).debounceTime(5000).timeout(5000).subscribe(...);
and in service:
createEmail(...): Observable<Json> {
return this.http
.post('url',
JSON.stringify(model),
{ headers: this.headers })
.delay(5000).debounceTime(5000).timeout(5000)
.map((response: Response) => {
return this.responseService.extractData(response);
})
.catch(error => {
return this.errorService.handleError(error);
});
}
didn't help me. Needed imports exist. Just js setInterval helped me.
How can I do delay before http request in other ways?
Upvotes: 3
Views: 6142
Reputation: 1513
You can use switchMap and timer:
createEmail(...): Observable<Json> {
return Observable
.timer(5000)
.switchMap(() =>
this.http.post(
'url',
JSON.stringify(model),
{headers: this.headers}
)
)
.map((response: Response) => {
return this.responseService.extractData(response);
})
.catch(error => {
return this.errorService.handleError(error);
});
}
Before the switchMap you can add debounceTime and another rx operator.
I invite you to check the documentation of switchMap to have more information: https://www.learnrxjs.io/operators/transformation/switchmap.html
You can use .delay
when you don't want delivered the result of the observable immediately. For example, I use it when I want simulate the delay of the response of the API.
Upvotes: 1