angular - 如何在 Angular 的 HttpClient 中使用 reportProgress?

标签 angular httpclient angular7

<分区>

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

  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 请求的一些进度。如果您想查看所有事件,包括传输进度,您需要使用observe: 'events'选项,并返回 HttpEvent 类型的 Observable。然后你可以在组件方法中捕获所有的events(DownloadProgress, Response..etc)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' },
      )
    });
  }

然后在组件中您可以捕获所有事件,如下所示。

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 Here.

关于angular - 如何在 Angular 的 HttpClient 中使用 reportProgress?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54896501/

相关文章:

json - Bad Request -Post 方法 - JSON DateTime 问题

javascript - 如何将响应式(Reactive)表单数据存储到本地存储?

angular 7.0.5 ng new 不问你想添加 Angular 路由吗?....等

Angular 5 管道和动态语言环境

HttpClient 没有重复使用我的连接,不断创建新的连接

java - HttpClient 中的授权承载 token ?

Angular 7 错误引用错误 : SystemJS is not defined

Angular 2 从休息服务下载文件

具有可选参数的 Angular 路由

angular - 仅在当前 PageSize 上选择 Mat-Table?