簡體   English   中英

如何在 Rxjs Angular 中訂閱可觀察對象 function 時處理錯誤並返回可觀察對象

[英]How to handle error and return observable while subscribe inside an observable function in Rxjs Angular

我想在一個可觀察對象中檢查一個 api 調用,我將在一個組件中訂閱它。 如下所述,我想以這種方式運行我的可觀察對象,但它不起作用。 我應該對此代碼做哪些更改才能使其正常工作。 每當我嘗試通過它進行訂閱時,尤其是在 someObservableWrittenInTheSameService 返回錯誤 404 的情況下,我都想返回 url2。

getfunction(submissionId: string ){

if (some condition) {
   this.someObservableWrittenInTheSameService(parameter).subscribe(
    (httpValue: any) => {
      let url = '';
      if (httpValue.code === 200) {
         return this.http.get(url1); 
      }
    }, err => {
      if (err.code === 404) {
        return this.http.get(url2);
      }
      
    }
  )
}

  let url3
  return this.http.get(url3);
}

然后在訂閱它的組件中調用此 function。 但是每當 someObservableWrittenInTheSameService 返回 404 時,訂閱總是失敗並且 go 到組件中的錯誤塊。

  1. 您可以使用 RxJS iif function 有條件地返回一個可觀察對象。
  2. 使用 RxJS 高階映射運算符switchMap到 map 從一個可觀察到另一個。 更多信息在這里
  3. 使用catchError運算符執行錯誤處理。 從它的正文中,您可以返回 HTTP 請求或轉發錯誤(使用throwError ),甚至可以根據您的要求完成可觀察的(使用EMPTY常量)。

嘗試以下

import { Observable, EMPTY, iif, throwError } from 'rxjs';
import { switchMap, catchError } from 'rxjs/operators';

getfunction(submissionId: string): Observable<any> {      // <-- observable must be returned here
  const obs1$ = this.someObservableWrittenInTheSameService(parameter).pipe(
    switchMap((httpValue: any) => 
      iif(
        () => httpValue.code === 200,
        this.http.get(url1),
        EMPTY                                             // <-- complete the observable if code is other than 200
      )
    ),
    catchError((error: any) =>                            // <-- `catchError` operator *must* return an observable
      iif(
        () => error.code === 404,
        this.http.get(url2),
        throwError(error)                                 // <-- you could also return `EMPTY` to complete the observable
      )
  )

  const obs2$ = this.http.get(url3);

  return iif(
    () => someCondition,
    obs1$,
    obs2$
  );
}

在這種情況下,您將訂閱使用它的getFunction() function。

例如。

this.getFunction('some value').subscribe({
  next: (value: any) => { },
  error: (error: any) => { },
  complete: () => { }
});

暫無
暫無

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

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