【问题标题】:How to take some actions while the response is pending in an http call in angular 2?如何在 Angular 2 的 http 调用中等待响应时采取一些措施?
【发布时间】:2016-12-22 10:23:48
【问题描述】:

我有一个 http 调用,它会在某个时间返回响应。在等待响应时,我想向用户显示一条消息或添加一个微调器,告诉用户等待响应。如何在角度 2 中做到这一点?

【问题讨论】:

标签: angular angular2-http


【解决方案1】:

在 HTML 中制作一些像这样的加载器:

<div *nfIf="loader">
// some svg or whatever you want to represent loader
<div>

在 HTTP 调用中将加载变量设为 true,在响应时将其设为 false。

public getData(anyParam: any): Observable<any> {
   this.loader = true;
   return this.http.get('anyUrl')
     .do(response => {
        // we are done! stop spinner !
        this.loader = false;
     })
     .map(...);
}

【讨论】:

    【解决方案2】:

    我猜你会为此实现一个Service (https://angular.io/docs/ts/latest/tutorial/toh-pt4.html)。

    所以会有一个函数getData():

    public getData(anyParam: any): Observable<any> {
      // start spinner !
      return this.http.get('anyUrl')
         .do(response => {
            // we are done! stop spinner !
         })
         .map(...);
    }
    

    【讨论】:

      【解决方案3】:
      _msgPopup.show("Wait while fetching data"); // Show popup
      _http.get('anshumanpatil.com').subscribe(res=>{
          _msgPopup.hide(); //call ended
      });
      

      【讨论】:

        【解决方案4】:

        解决您的问题的方法是在启动请求之前声明一个变量(或显示微调器或其他任何内容),然后在请求完成时将其隐藏。

        您的代码将类似于:

        this.isLoading = true;
        this.get().finally(() => this.isLoading = false);
        

        它会直接显示然后隐藏它,下一部分只是处理模板中的ngIf显示。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-05-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-11-22
          • 2020-08-21
          • 2012-01-15
          相关资源
          最近更新 更多