我有点卡住了,原来我有一个函数来发射一个post请求,并返回一个我的响应接口的可观察对象:
post(url:string) : Observable<ApiResponseInterface>
{
return this.httpClient.post(url);
}
现在当我添加报告进度和监控事件的功能时,它现在想返回Observable
我不确定我怎样才能捕捉到进度的事件,同时还能返回我的ApiResponseInterface的可观察值。
我可以为进度订阅HttpEvent可观察事件
this.httpClient.post(url,{reportProgress:true, observe: “events”}).subscribe((event:HttpEvent)=>{
// update progress bar
});
这一切都很好,但是在它完成之后,我想在软件的其他部分使用我的正常的可观察变量。我怎样才能做到这一点呢?我猜想有一种方法可以在http请求完成后返回我的观察变量,但我不确定在这种情况下如何做。
试试angular doc的解决方案:
这取决于你想在哪里处理进度条的更新。但让我们说,你想直接在你的发布方法中做这个。在这种情况下,rxjs tap操作符是一个很好的工具,可以在继续向订阅者发送响应之前对其做一些处理。 而使用rxjs last操作符只返回最后发出的值,在这种情况下就是完整的事件。
post() {
this.http.request(req).pipe(
tap(event => {
if (event.type == HttpEventType.UploadProgress) {
// update the progress bar
}
}),
last() // return last (completed) message to caller
);
}
https://angular.io/guide/http#tracking-and-showing-request-progress