SD.
SD.

Reputation: 9549

How to call both next and error on RxJS Observable

If you have an API (like GraphQL) that allows for graceful failures where both data and error is returned, is there a way to call both the happy and the error path of an Observable.

Service:

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

Caller:

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

Is there a neat way to pipe / map the result and call both callback functions?

Upvotes: 2

Views: 1911

Answers (2)

TheFlorinator
TheFlorinator

Reputation: 124

It sounds like you want to be able to get a value you back to your caller from your fetch when the API returns an error. You could try something like this

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

All error responses will be caught by the catchError and then Observable will be returned. Then in your caller you can do something like this

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

Upvotes: 0

benshabatnoam
benshabatnoam

Reputation: 7640

You can wrap your fetchData func in an Observable.

Service:

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 DEMO

Upvotes: 1

Related Questions