Angular HttpClient - show spinner/progress indicator while waiting for service to respond - progress events

后端 未结 2 1311
太阳男子
太阳男子 2020-12-29 00:15

I\'m switching over my service calls to use the new HttpClient. I\'m struggling with 3 things

  1. Figure out how to show a spinner/progress bar/etc while waiting f
相关标签:
2条回答
  • 2020-12-29 00:41

    Create a spinner component using the below code

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

    In your main component, add the component markup as below

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

    In your typescript code

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

    show the spinner where you are making the service call, for example onInit of the component

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

    LIVE DEMO

    0 讨论(0)
  • 2020-12-29 00:54

    I've combined @aravind answer and this post (https://alligator.io/angular/httpclient-intro/) to piece together a solution. This leverages Angular's Http client progress events to turn the spinner on/off and also handles errors.

    component:

    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('                                                                    
    0 讨论(0)
提交回复
热议问题