我正在使用 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.