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

Ash*_*oyi 19 http interceptor angular2-http angular

有许多adhoc库支持angular2的上传/下载进度,我不知道如何使用native angular2 http api在上传/下载时显示进度.

我想使用原生http api的原因是因为我想利用它

  1. 本机http api周围的http拦截器(http API包装器),用于验证,缓存和丰富正在发送的http请求,例如this&this
  2. 除了angular之外,http api比任何adhoc API都强大得多

一篇关于如何使用angular的http api进行上传/下载的好文章

但该文章提到,没有本土方式来支持进步.

有没有人尝试使用http api来显示进度?

如果没有,你知道角度回购中的问题吗?

Edm*_*ues 43

由于角的4.3.x及以后的版本,它可以使用新的实现的HttpClient@angular/common/http.

阅读听取进度事件部分.

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

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

而对于下载,它可能是几乎相同的东西:

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

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