如何在 Angular 的 HttpClient 中使用 reportProgress? [英] How to use reportProgress in HttpClient in Angular?
问题描述
我正在使用 HTTP
POST
方法下载文件.我想调用另一种方法向最终用户显示下载进度,直到文件下载完成.如何在 HttpClient
中使用 reportProgress
为此.
I am downloading file using HTTP
POST
method. I want to call another method to show download progress to end user until file download complete.
How to use reportProgress
in HttpClient
for this.
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'
选项并返回 Observable
类型的 HttpEvent
.然后您可以在组件方法中捕获所有 events(DownloadProgress, Response..etc)
.在 Angular 官方文档中查找更多详细信息.
You need to use reportProgress: true
to show some progress of any HTTP
request. If you want to see all events, including the progress of transfers
you need to use observe: 'events'
option as well and return an Observable
of type HttpEvent
. Then you can catch all the events(DownloadProgress, Response..etc)
in the component method.
Find more details in 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' },
)
});
}
然后在组件中您可以捕获所有事件
,如下所示.
Then in component you can catch all the events
as below.
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.
这篇关于如何在 Angular 的 HttpClient 中使用 reportProgress?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!