简体   繁体   English

Angular 5 http客户端,在订阅时执行功能

[英]Angular 5 http client, execute function on subscribe

I want to show loading spinner while processing http request. 我想显示在处理http请求时正在加载微调框。 But i have an issue, because spinner called when I return observable even if there no active subscribers. 但是我有一个问题,因为即使我没有活动的订阅者,当我返回observable时,微调器也会调用。 How to call showSpinner() function only when someone subscribe to http? 仅当有人订阅http时如何调用showSpinner()函数?

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: 您可以使用defer()函数仅在调用subscribe()时创建实际的可观察对象,从而在那时显示微调器:

return defer(() => {
  this.showSpinners();
  return this.http.post(this.apiUrl+type, args);
});

You can wrap the HTTP call this.http.post with defer . 您可以使用defer包装HTTP调用this.http.post This is RxJS 6 example: 这是RxJS 6示例:

import { defer } from 'rxjs';

private request(type, args={}){
  return defer(
    () => {
      this.showSpinner();
      return this.http.post(this.apiUrl+type,args);
    })
    .pipe(
      finalize(() => this.hideSpinner()),
    );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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