How to use reportProgress in HttpClient in Angular? [duplicate]
Asked Answered
T

2

31

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' },
      )
    });
  }
Tensive answered 27/2, 2019 at 1:7 Comment(0)
G
66

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.

Gertrudegertrudis answered 27/2, 2019 at 7:11 Comment(5)
how do I configure the package bytes amount for each part of the file?Shcherbakov
@Sérgio S. Filho could not get what you are askingGertrudegertrudis
Hello! in order to send a file to the server in parts, the client app will break the file in some smaller amounts of bytes. I was looking for how to configure the size of each of these small packages of bytes. I think it could increase or decrease the visual feedback percentage precision. And maybe help to show a smoother loading feedback.Shcherbakov
Does the server/backend need to be configured in a certain way? As in, return a stream or report progress?Dollfuss
@Dollfuss No dependency for the backend from this change.Gertrudegertrudis
P
3

you will have to add HttpClientModule in your AppModule

you first need to build a request object by creating an instance of HttpRequest class and using reportProgress option.

For more information, please refer: https://alligator.io/angular/httpclient-intro/

Persistent answered 27/2, 2019 at 3:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.