簡體   English   中英

rxjs:如何從 catchError 返回另一個可觀察的結果

[英]rxjs: how to return the result from another observable from catchError

我正在使用 rxjs 6.5 和 angular。 基本上,我想在我的服務中有一個方法:

  • 如果 api 響應,則從第一個 api 調用返回狀態
  • 如果第一個調用失敗,則從第二個(不同的)api 調用返回狀態
  • 如果第二次調用失敗,則返回一個虛擬值

這是我到目前為止所擁有的。 我想我需要使用flatMap/mergeMap ,但我不知道如何使用。

服務.ts

public getStatus()
  {
    return this.http.get('http://api.com/status1')
      .pipe(
        catchError(() => {
            //makes 2nd api call here
            return this.http.get('http://api.com/status2')

            .pipe(catchError(() =>
            {
              //both calls failed
              return of({
                  data: 'blah',
                  success: false
                });

            }))

        }));
  }

組件.ts

this.service.getStatus().subscribe(status=>this.status = status);

有人可以幫忙嗎?

您的方法有效,但嵌套管道看起來不太好。 不過,您可以做一件簡單的事情:

      // Use 'of' operator to "fake" a successful API call.
      // Use 'throwError' operator to "fake" a failed API call.
      public getStatus()
      {
        return of('firstApiCall')
          .pipe(
            catchError(() => {
              //makes 2nd api call here
              return of('secondApiCall')
            }),
            catchError(() =>
              {
                //both calls failed
                return of({
                    data: 'blah',
                    success: false
                  });
              })
          );
      }

您可以提取第二個catchError塊以將所有運算符都放在一個級別上 - catchError運算符只會在 observable 引發錯誤時觸發,並且由於您希望對每次調用進行不同的錯誤處理,因此可以這樣做。

可能你也可以只用一個catchError塊來處理它,並對請求 URL 進行一些檢查以確定你想要返回什么,但我想這需要更多的邏輯並且不值得。

請查看提供的 stackblitz 以查看其實際效果:

https://stackblitz.com/edit/angular-rfevnt

暫無
暫無

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

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