Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

angular

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 for a response from a post, get, put.
  2. Fake a slow response
  3. Is it possible to use the new progress events to trigger this sort of functionality?

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)
}
like image 481
Anthony Avatar asked Aug 04 '17 17:08

Anthony


1 Answers

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

like image 169
Aravind Avatar answered Oct 29 '22 14:10

Aravind