Angular HttpClient - 在等待服务响应时显示微调器/进度指示器 - 进度事件

标签 angular

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

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

应用程序.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) {

      }
    }
  )

应用程序.服务.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)
}

最佳答案

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

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>

在你的 typescript 代码中

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

关于Angular HttpClient - 在等待服务响应时显示微调器/进度指示器 - 进度事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45512285/

相关文章:

javascript - 在 Angular Material 中关闭多选下拉菜单时触发事件

angular - 来自 chokidar 的错误(C :\): Error: EBUSY: resource busy or locked, lstat 'C :\DumpStack. log.tmp

javascript - 如何通过@input 属性应用样式,我想增加 mat-autocomplete 的宽度

javascript - 通过 ngModel 在两个输入字段之间共享数据

html - 如何将点击事件添加到 typescript 中动态添加的html元素

angular - 将枚举与方法合并

ios - (iOS) 从非 ascii 键捕获事件

jquery - Angular 2 : Controlling SVG Image/Icon Css Styles dynamically through user inputs/events on UI

javascript - 复制而不保留引用

angular - 即使未选择任何值,如何在表单中标记 ngbDatepicker 有效