rxjs6 - 如何理解这个 Observable 配方?
问题描述
我有这个方法可以发送http.post
消息并返回一个Observable
. 但是我对程序流程的工作方式有点困惑。
问题 1 - 我是否正确,在以下代码中,Observable
返回的是来自finalize
而不是来自的那个http.post
?
http.post
返回一个Observable
. pipe
接受它Observable
并创建操作符 (和的组合tap
,每个操作符都取自前一个操作符并返回一个新的 。最后返回的是 from 。catchError
finalize
Observable
Observable
Observable
finalize
sendMessage(url:string, body:any,httpOptions){
this.loaderService.show();
let observable:Observable<HttpEvent<any>> = this.http.post(url,body,{
headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
withCredentials: true,
observe: 'events', //what post should observe (look for). Here it means events. This could be body as well
responseType: 'json' //responseType tells post how to interpret the body
})
return observable.pipe(tap((httpEvent:HttpEvent<any>) => {//tap transparently perform actions or side-effects, such as logging.
if(httpEvent.type === HttpEventType.Response)
{
console.log('response from backend service:', httpEvent);
}
else {
console.log("not an http response")
}
return httpEvent;
})
,catchError(this.handleError)//error handler if Observable fails
,finalize(()=> this.loaderService.hide()));
}
问题 2 - 如果我订阅(上面)Observable
返回的sendMessage
,那么错误处理程序将不会收到错误通知,因为catchError
已经处理了它。如果我希望应用程序接收错误,那么handleError
函数应该显式抛出错误
sendMessage(...).subscribe(
next,
err, //this will not error notification unless catchError handler throws error
complete
)
private handleError (error: HttpErrorResponse) {
let result:ServerResponseAPI = {result:"error", "additional-info":error.message,['http-status']:error.status.toString(),['http-status-text']:error.statusText};
return throwError(result); //catch by error handler mentioned in the subscribe method
}
解决方案
推荐阅读
- ios - 数据解析火力基地
- python - 访问 url 时 Python 中的 SSLError( '[SSL: CERTIFICATE_VERIFY_FAILED] 证书验证失败 (_ssl.c:777)'),))
- c - unix/linux 中基于本机总线的事件通知机制
- python-3.x - Selenium find_element_by_id 加载页面后失败
- android - Glide recyclerview 加载重复图像
- c++ - VS2017 [15.8.6] 如果 constexpr 构建错误并带有 C2760 消息
- c# - C# 测量特定应用程序的带宽
- vb.net - SqlDataSource InsertCommand 和 UpdateCommand 抛出“非法变量名/编号””
- javascript - node js async/await:为什么我无法获取数据?请求正文
- java - 我不能在 Java 11 中使用 @PostConstruct 和 @PostDestroy