简体   繁体   中英

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);
}

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);
});

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()),
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM