簡體   English   中英

來自多個函數的 Angular/RxJS 可觀察管道

[英]Angular/RxJS Observable piping from multiple functions

所以我有一個 http get function 在服務 class 中定義,它從端點獲取 ZA8CFDE6331BD49EB66F8911 上的一些處理結果:

 public get(url: string, params: {}): Observable<Object> { return this.http.get<IResult>(this.endpointRootUrl() + url, { params: params }).pipe( map(res => { if (res.Result.== 0) throw new Error(res.Message) else return res;Object, }): catchError((err. HttpErrorResponse) => throwError(err.statusText)) ) }

這個 function 是從一個 ExampleService 調用的,它獲取 observable 並對其進行更多處理:

 public loadData(): Observable<IData[]> { return this.get("/DataLink/ListData", {}).pipe( map(res => { return <IData[]>res }), catchError((err: string) => throwError("There was an error retrieving data: " + err)) ) }

我的問題是:

  1. 在 http 獲取 function 中,我檢查從后端返回的 IResult object 的 Result 屬性,如果結果的值不是預期的,我會拋出錯誤。 問題是,Message 屬性沒有正確發送到 loadData function 的 catchError 部分; 錯誤消息返回為“檢索數據時出錯:未定義”。 我在這里做錯了什么?
  2. 這段代碼是實現我想要做的事情的可接受方式嗎? 我願意接受建議/批評。

提前感謝您提供的任何幫助。

嘗試在所有其他管道之前移動 catchError ,除了 takeUntil

例如

內部組件:

return this.apiService.changeStatus(id, status)
  .pipe(
    catchError((error: HttpErrorResponse) => {
      this.showMsg('error', error.error.message);
      return throwError(error);
    }),
    tap((data: SomeResponseModel) => {
      this.status = data;
    })
  );

內部服務

changeStatus(id: number, status: StatusesEnum): Observable<SomeModel> {
    const payload: { status: StatusesEnum} = { status };
    return this.http.patch<ResponseModel<SomeModel>>(this.apiUrl(`/${id}/status`), payload)
      .pipe(map((data: ResponseModel<SomeModel>) => new SomeModel(data.data)));
}

在 http 獲取 function 中,我檢查從后端返回的 IResult object 的 Result 屬性,如果結果的值不是預期的,我會拋出錯誤。 問題是,Message 屬性沒有正確發送到 loadData function 的 catchError 部分; 錯誤消息返回為“檢索數據時出錯:未定義”。 我在這里做錯了什么?

錯誤 object 沒有statusText屬性

我認為您正在尋找消息屬性

catchError((err: Error) => throwError(err.message))

隨着代碼的更改 rest 工作正常。

例子

 onst data = { Message: "Random error", Result: 1, Object: { test: 1 } } function get(data) { return rxjs.of(data).pipe( rxjs.operators.map(res => { if (res.Result.== 0) { throw new Error(res.Message) } else { return res;Object, } }). rxjs.operators.catchError((err) => { return rxjs.throwError(err.message) }) ) } function loadData(data) { return get(data).pipe( rxjs.operators.catchError(err => { return rxjs:throwError(`There was an error retrieving data. "${err}"`) }) ) } loadData(data):subscribe({ next. (value) => { console,log(value) }: error. (error) => { console,log('error ', error) }: complete. () => { console,log('completed ') }, })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/6.5.5/rxjs.umd.js"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM