首页 > 解决方案 > 如何理解这个 Observable 配方?

问题描述

我有这个方法可以发送http.post消息并返回一个Observable. 但是我对程序流程的工作方式有点困惑。

问题 1 - 我是否正确,在以下代码中,Observable返回的是来自finalize而不是来自的那个http.post

http.post返回一个Observable. pipe接受它Observable并创建操作符 (和的组合tap,每个操作符都取自前一个操作符并返回一个新的 。最后返回的是 from 。catchErrorfinalizeObservableObservableObservablefinalize

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

  }

标签: rxjs6

解决方案


推荐阅读