Reputation: 437
I want to show loading spinner while processing http request. But i have an issue, because spinner called when I return observable even if there no active subscribers. How to call showSpinner() function only when someone subscribe to http?
private request(type, args={}){
this.showSpinner();
return this.http.post(this.apiUrl+type,args);
}
Upvotes: 1
Views: 403
Reputation: 96891
You can wrap the HTTP call this.http.post
with defer
. This is RxJS 6 example:
import { defer } from 'rxjs';
private request(type, args={}){
return defer(
() => {
this.showSpinner();
return this.http.post(this.apiUrl+type,args);
})
.pipe(
finalize(() => this.hideSpinner()),
);
}
Upvotes: 3
Reputation: 691635
You can use the defer() function to create the actual observable only when subscribe() is called, and thus show the spinner at that time:
return defer(() => {
this.showSpinners();
return this.http.post(this.apiUrl+type, args);
});
Upvotes: 3