http - 如何使用 angular2 http API 跟踪上传/下载进度

标签 http angular interceptor angular2-http

因此在angular2中有很多支持上传/下载进度的ad hoc库,我不知道如何在上传/下载时使用原生angular2 http api来显示进度。

我之所以要使用原生的http api是因为我想利用:

  1. 围绕原生 http api 的 http 拦截器(http API 包装器)验证、缓存和丰富正在发送的实际 http 请求,例如 this & this
  2. Angular 的 http api 比任何 ad hoc API 都要健壮得多

a nice article关于如何使用 angular 的 http api 进行上传/下载

但是文章提到没有原生的方式来支持进度。

有人试过使用 http api 来显示进度吗?

如果不是,您是否知道 Angular repo 中的问题?

最佳答案

从 Angular 4.3.x 及更高版本开始,可以使用新的 HttpClient 来实现来自 @angular/common/http

阅读Listening to progress events部分。

简单的上传示例(从上面提到的部分复制):

    const req = new HttpRequest('POST', '/upload/file', file, {
      reportProgress: true,
    });

    http.request(req).subscribe(event => {
      // Via this API, you get access to the raw event stream.
      // Look for upload progress events.
      if (event.type === HttpEventType.UploadProgress) {
        // This is an upload progress event. Compute and show the % done:
        const percentDone = Math.round(100 * event.loaded / event.total);
        console.log(`File is ${percentDone}% uploaded.`);
      } else if (event instanceof HttpResponse) {
        console.log('File is completely uploaded!');
      }
    });

对于下载,它可能几乎是一样的:

    const req = new HttpRequest('GET', '/download/file', {
      reportProgress: true,
    });

    http.request(req).subscribe(event => {
      // Via this API, you get access to the raw event stream.
      // Look for download progress events.
      if (event.type === HttpEventType.DownloadProgress) {
        // This is an download progress event. Compute and show the % done:
        const percentDone = Math.round(100 * event.loaded / event.total);
        console.log(`File is ${percentDone}% downloaded.`);
      } else if (event instanceof HttpResponse) {
        console.log('File is completely downloaded!');
      }
    });

请记住,如果您正在监控下载,则必须设置 Content-Length,否则无法测量请求。

关于http - 如何使用 angular2 http API 跟踪上传/下载进度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42231123/

相关文章:

http - 3.8 分钟后准确获取 http 响应,状态代码为 500 OK

select/ngFor 中的 angular5 分组输出

css - 每个组件的样式 mat-select-value

angular - 如何在 Angular httpclient中发送FormData和请求正文

java - ActionMappingParametersInteceptor - 为什么我需要它

HTTP接受协商算法

javascript - 如何将 HTTP 请求映射或关联到 Node.js 中的数据库调用?

c# - 如何在返回前等待回调

java - 拦截器在spring中的使用

header - 如何使用 Interceptor 添加 Mule header ?