簡體   English   中英

Promise to Observable無法正確捕獲錯誤

[英]Promise to Observable does not catch error correctly

我有以下功能。 我從中刪除了不必要的代碼,以使其更易於閱讀。

add() {
    const listingId = 'xyz';

    const promise = new Promise((resolve, reject) => {
      reject(Error(`error msg`));
    });

    return from(promise).pipe(
      map(() => listingId),
      catchError(error => of(error.message))
    );
  }

我正在訂閱這樣的可觀察對象:

this.service.add().subscribe(
      listingId => {
        console.log(`listingId:`, listingId);
      },
      error => {
        console.log(`Error:`, error);
      },
      () => {
        console.log(`Completed`);
      }
    );

問題在於錯誤是在next()而不是error()中捕獲的。 控制台輸出為:

listingId: error msg
Completed

它應該是:

Error: error msg

我究竟做錯了什么?

在這一行中catchError(error => of(error.message))使用catchError捕獲錯誤,並且在流切換到of(error.message)catchError類似於switchMap ,您處理錯誤並切換到另一個可觀察到的

暫無
暫無

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

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