如何在Angular的HttpClient中使用reportProgress? [英] How to use reportProgress in HttpClient in Angular?

查看:497
本文介绍了如何在Angular的HttpClient中使用reportProgress?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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

然后在组件中,您可以捕获所有的events,如下所示.

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");
        }
});

在此处查找 HttpEventTypes.

Find HttpEventTypes Here.

这篇关于如何在Angular的HttpClient中使用reportProgress?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆