Evgenii Malikov
Evgenii Malikov

Reputation: 437

Angular 5 http client, execute function on subscribe

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

Answers (2)

martin
martin

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

JB Nizet
JB Nizet

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

Related Questions