【问题标题】:Angular HttpClient - show spinner/progress indicator while waiting for service to respond - progress eventsAngular HttpClient - 在等待服务响应时显示微调器/进度指示器 - 进度事件
【发布时间】:2017-08-05 05:16:18
【问题描述】:

我正在切换我的服务调用以使用新的 HttpClient。我在 3 件事上苦苦挣扎

  1. 弄清楚如何在等待时显示微调器/进度条/等 对于帖子的回复,获取,放置。
  2. 假装响应缓慢
  3. 是否可以使用新的进度事件来触发此类功能?

application.component.ts

 this.applicationFormService.putForm(formModel)    
  .subscribe(
    // Successful responses call the first callback.
    (res) => this.goToRoute(res),
    // Errors will call this callback instead:
    (err: HttpErrorResponse) => {
      if (err.error instanceof Error) {
        console.log("Client-side error occured.");
      } else {
        console.log("Server-side error occured.");
      }
    },
    //Tried adding progress event logic here but I get error Argument of type '(event: any) => void' is not assignable to parameter of type '() => void'. Is this totally the wrong implementation and can it even be used for showing progress?
    event => {
      // Via this API, you get access to the raw event stream.
      // Look for upload progress events.
      if (event.type === HttpEventType.UploadProgress) {
        // This is an upload progress event.
      } else if (event instanceof HttpResponse) {

      }
    }
  )

application.service.ts

constructor (private httpNew: HttpClient){}
putForm(applicationForm:any){
 this.applicationId = this.id.id
 const req = new HttpRequest('PUT', this.applicationSubmitUrl+this.applicationId, applicationForm, {
  reportProgress: true,
 });
return this.httpNew.request(req)
}

【问题讨论】:

    标签: angular


    【解决方案1】:

    使用以下代码创建一个微调器组件

    import { Component, Input } from '@angular/core';
    
    @Component({
        selector: 'spinner',
        template:
        ` <div *ngIf="show">
              <span><i class="fa fa-spinner fa-spin" [ngStyle]="{'font-size': size+'px'}" aria-hidden="true"></i></span>
          </div>
        `
    })
    export class SpinnerComponent {
        @Input() size: number = 25;
        @Input() show: boolean;
    
    
    }
    

    在您的主组件中,添加组件标记如下

    <spinner [show]="showSpinner" [size]="150"> </spinner>
    

    在你的打字稿代码中

    this.applicationFormService.putForm(formModel)    
      .subscribe(data=>{
            ....
           // hide the spinner
           this.showSpinner = false;
    
        }(err: HttpErrorResponse) => {
           this.showSpinner = false;          
        })
    

    显示你在哪里进行服务调用的微调器,例如组件的 onInit

    ngOnInit(){
       this.showSpinner = true;
       ...service call logics...
    }
    

    LIVE DEMO

    【讨论】:

    • 这正是我正在寻找的关于问题 #1 的内容将分享我提出的将您的答案与我的答案相结合的解决方案。谢谢!
    • 那么您需要更多帮助吗?
    【解决方案2】:

    我已将@aravind 答案和这篇文章 (https://alligator.io/angular/httpclient-intro/) 结合起来,拼凑出一个解决方案。这利用了 Angular 的 Http 客户端进度事件来打开/关闭微调器并处理错误。

    组件:

    showSpinner = false;
    this.shortFormService.postShortForm(formModel)
      .subscribe(      
    
        (event: HttpEvent<any>) => {
          console.log(event)
          switch (event.type) {
            case HttpEventType.Sent:
              this.showSpinner = true;
              console.log('Request sent!');
              break;
            case HttpEventType.ResponseHeader:
              console.log('Response header received!');
              break;
            case HttpEventType.UploadProgress:
              const percentDone = Math.round(100 * event.loaded / event.total);
              console.log(`File is ${percentDone}% uploaded.`);
            case HttpEventType.DownloadProgress:
              const kbLoaded = Math.round(event.loaded / 1024);
              console.log(`Download in progress! ${ kbLoaded }Kb loaded`);
              break;
            case HttpEventType.Response:
              console.log('? Done!', event.body);
              this.showSpinner = false;            
    
          }
        },
        (err: HttpErrorResponse) => {
          if (err.error instanceof Error) {
            console.log("Client-side error occured.");
          } else {
            this.router.navigate(['/error', err.error.error]);
            console.log("Server-side error occured.");
          }
        }
      )
    
    }
    

    服务:

    postShortForm(shortForm: any) {
     const req = new HttpRequest('POST', this.preCheckUrl, shortForm, {
      reportProgress: true,
    });
    return this.httpNew.request(req)
      .retry(3)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-29
      • 2010-11-16
      相关资源
      最近更新 更多