Home > Mobile >  How to handle error and return observable while subscribe inside an observable function in Rxjs Angu
How to handle error and return observable while subscribe inside an observable function in Rxjs Angu

Time:03-08

I want to check one api call inside an observable which I will subscribe in a component. As written below, I want to run my observable in this manner but it is not working. What changes shall I do to this code to make it work. Whenever I try to subscribe through it especially through the scenario when someObservableWrittenInTheSameService returns with an error 404, I want to 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);
}

This function is then is called in a component where it is subscribed. But whenever someObservableWrittenInTheSameService return 404, the subscription always fails and go to error block in the component.

CodePudding user response:

On the surface this problem seems easy - create a pipe that has a catchError operator at the end that returns the result from url2 if there was a 404. However, there is a catch, because presumably the result from url1 could also return a 404, and it is unclear in that case if you would still want the result from url2 to be returned.

If the case above is unacceptable, you need to catch the error before that call to get url1. In the example below I use a simple result code, but if necessary the body from the initial result can be incorporated by changing the mapTo to a map.

this.someObservableWrittenInTheSameService(parameter).pipe(
  mapTo({ isFound: true }),
  catchError(err => (err?.code === 404) ? of({ isFound: false }) : throwError(err)),
  switchMap(({ isFound }) => isFound ? this.http.get(url1) : this.http.get(url2))
);

CodePudding user response:

  1. You could use RxJS iif function to return an observable conditionally.
  2. Use RxJS higher order mappping operator switchMap to map from one observable to another. More info here.
  3. Use 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 constant) based on your requirement.

Try the following

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$
  );
}

In this case you'd subscribe to the getFunction() function where it's used.

For eg.

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