如何在Angular的HttpClient中使用reportProgress?

kar*_*aja 5 httpclient angular angular7

我正在使用HTTP POST方法下载文件。我想调用另一种方法来向最终用户显示下载进度,直到文件下载完成。如何使用reportProgressHttpClient此。

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

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

Sud*_*nda 13

您需要使用reportProgress: true来显示任何HTTP请求的进度。如果要查看,all events, including the progress of transfers还需要使用observe: 'events'option并返回Observabletype HttpEvent。然后,您可以捕获events(DownloadProgress, Response..etc)component方法中的所有内容。 Angular官方文档中找到更多详细信息。

  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' },
      )
    });
  }
Run Code Online (Sandbox Code Playgroud)

然后在组件中,您可以捕获所有events如下内容。

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

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

在此处查找HttpEventTypes。

  • 如何配置文件每个部分的包字节数? (2认同)