如何在 Rxjs Angular 中的可观察函数内订阅时处理错误和 return 可观察

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

我想检查一个 api 在我将在组件中订阅的可观察对象中的调用。如下所述,我想以这种方式 运行 我的可观察对象,但它不起作用。我应该对此代码做哪些更改才能使其正常工作。每当我尝试通过它订阅时,尤其是在 someObservableWrittenInTheSameService returns 出现错误 404 的情况下,我想 return 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);
}

然后在订阅它的组件中调用此函数。但是每当 someObservableWrittenInTheSameService return 404 时,订阅总是失败并转到组件中的错误块。

  1. 您可以使用 RxJS iif 函数有条件地 return 一个可观察对象。
  2. 使用 RxJS 高阶映射运算符 switchMap 从一个 observable 映射到另一个。更多信息 .
  3. 根据您的要求使用 catchError operator to perform error handling. From it's body you could either return the HTTP request or forward the error (using throwError) or even complete the observable (using 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() 函数。

例如

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