簡體   English   中英

如何在 RxJS Observable 上同時調用 next 和 error

[英]How to call both next and error on RxJS Observable

如果您有一個 API(如 GraphQL),允許在返回dataerror情況下正常失敗,有沒有辦法同時調用 Observable 的快樂和錯誤路徑。

服務:

public fetchData: Observable<any> {
    return myApi.fetch().pipe(map(result => {
        if (result.data) {
            // call happy path here
        }   
        if (result.error) {
            // call error path (as well) here
        } 
    }));
}

呼叫者:

myService.fetchData().subscribe(
    next => {
        // this is called
    }, error => { 
        // as well as this
    });

有沒有一種巧妙的方法來管道/映射結果並調用兩個回調函數?

您可以將fetchData函數包裝在Observable

服務:

public fetchData: Observable<any> {
    return new Observable(observer => {
        myApi.fetch().subscribe(
            result => {
                observer.next(result.data); // call happy path here
                if (result.error) {
                    observer.error(result.error); // call error path (as well) here
                }
            }
        );
    });
}

StackBlitz 演示

聽起來您希望能夠在 API 返回錯誤時從 fetch 中獲取返回給調用方的值。 你可以試試這樣的

public fetchData: Observable<successObject | boolean> {
  return myApi.fetch().pipe(
    map(result => {
      if (result.data) {
        // call happy path here
      }   
    }),
    catchError(() => {
      // catch API errors here and return false
      return of(false);
    })
  );
}

所有錯誤響應都會被 catchError 捕獲,然后返回 Observable。 然后在你的來電者中你可以做這樣的事情

myService.fetchData().subscribe(response => {
  if(!response) {
    // error state
  }
  // success state
});

暫無
暫無

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

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