0

I have the following code:

  myFunction() {
    this.store$
      .select(selectFoo, this.fooId)
      .pipe(
        switchMap(foo =>

          // THE FOLLOWING API CALL RESULTS IN A 404

          this.apiService.someApiCall(foo)
            .pipe(
              catchError(error => {
                alert("There was an error!");
                return of(null);
              })
            )
        )
      )
      .subscribe(() => {
        alert("We are in the subscribe block, proceed assuming success");
      });
  }

When I set it up to cause an error in this.apiServce.someApiCall, e.g. a 404, the error alert happens, but also the alert in the subscribe block.

I would want it to abort in case of error and not go in the subscribe block, where I would handle the "success" case.

What am I missing?

Thanks!

Salvatore Iovene
  • 2,064
  • 1
  • 17
  • 31
  • The `Observable` will always subscribe to get success or error without subscribing api call will never trigger – Kamran Khatti Jul 29 '21 at 14:10
  • The API call is in a `switchMap` and it DOES get triggered. – Salvatore Iovene Jul 29 '21 at 14:12
  • 1
    Take note on comments in the accepted answer (especially [this](https://stackblitz.com/edit/rxjs-catcherror-withmapoperators) stackblitz) and other answers, which explain the difference about catchError on the inner observable and outer observable. – TotallyNewb Jul 29 '21 at 14:17
  • 1
    It is actually handling error callback - Ideally you should handle success and error cases in different callbacks - .subscribe( data => console.log(data), err => console.log(err), () => console.log('complete ') ); – MBB Jul 29 '21 at 16:21
  • Thank you @MBB, by removing the `catchError` and handling the error as you suggested, my problem is solved. Alternatively, if I return `EMPTY` from the `catchError`, it's also solved. – Salvatore Iovene Jul 29 '21 at 16:53

0 Answers0