因此在angular2中有很多支持上传/下载进度的ad hoc库,我不知道如何在上传/下载时使用原生angular2 http api来显示进度。
我之所以要使用原生的http api是因为我想利用:
- 围绕原生 http api 的 http 拦截器(http API 包装器)验证、缓存和丰富正在发送的实际 http 请求,例如 this & this
- 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/