How to use reportProgress in HttpClient in Angular?

karthik thurairaja picture karthik thurairaja · Feb 27, 2019 · Viewed 15.1k times · Source

I am downloading file using HTTP POST method. I want to call another method to show download progress to end user until file download complete. How to use reportProgress in HttpClient for this.

  downfile(file: any): Observable<any> {

    return this.http.post(this.url , app, {
      responseType: "blob", reportProgress: true, headers: new HttpHeaders(
        { 'Content-Type': 'application/json' },
      )
    });
  }

Answer

Sudarshana Dayananda picture Sudarshana Dayananda · Feb 27, 2019

You need to use reportProgress: true to show some progress of any HTTP request. If you want to see all events, including the progress of transfers you need to use observe: 'events' option as well and return an Observable of type HttpEvent. Then you can catch all the events(DownloadProgress, Response..etc) in the component method. Find more details in Angular Official Documentation.

  downfile(file: any): Observable<HttpEvent<any>>{

    return this.http.post(this.url , app, {
      responseType: "blob", reportProgress: true, observe: "events", headers: new HttpHeaders(
        { 'Content-Type': 'application/json' },
      )
    });
  }

Then in component you can catch all the events as below.

this.myService.downfile(file)
    .subscribe(event => {

        if (event.type === HttpEventType.DownloadProgress) {
            console.log("download progress");
        }
        if (event.type === HttpEventType.Response) {
            console.log("donwload completed");
        }
});

Find HttpEventTypes Here.