如何在 Angular 的 HttpClient 中使用 reportProgress? [复制]

2023-12-21

我正在使用下载文件HTTP POST方法。我想调用另一种方法向最终用户显示下载进度,直到文件下载完成。 如何使用reportProgress in HttpClient为了这。

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

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

你需要使用reportProgress: true显示任何进展HTTP要求。如果你想看all events, including the progress of transfers你需要使用observe: 'events'选项以及返回Observable类型的HttpEvent。然后你就可以捕捉到所有的events(DownloadProgress, Response..etc)在组件方法中。查找更多详细信息Angular 官方文档 https://angular.io/guide/http#listening-to-progress-events.

  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' },
      )
    });
  }

然后在组件中你可以捕获所有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");
        }
});

Find HttpEventType 在这里。 https://angular.io/api/common/http/HttpEventType

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Angular 的 HttpClient 中使用 reportProgress? [复制] 的相关文章

随机推荐