Reputation: 5939
I'm having a lot of difficulty with this concept. I have 2 forms which can be handled by the same xhr call. So I'm sending the form submissions through a common stream and switching to an xhr call. I'm attempting to use catchError to handle any 500s, which DOES work (the .publish(error) call puts up a dialog w/ the error message), but then the subscription immediately completes! I thought this would continuously take input from the search$ stream until I called this.search$.complete()
(which happens on componentDestroy). What am I missing about 'catch and continue listening' with RXJS?
this.search$.pipe(
tap(() => this.pending = true),
switchMap(criteria => this._dealer.search(criteria)),
catchError(ErrorNotifierService.catchResponseErrorAsObservable)
).subscribe(response => {
this.pending = false;
if (ErrorNotifierService.isCaughtError(response)) {
this._error.publish(ErrorNotifierService.getErrorNotification(response.error));
} else {
this.dsSearchResults.data = response;
}
}, () => console.log('subscribe errored'), () => console.log('subscribe completed?'));
Upvotes: 0
Views: 104
Reputation: 20063
You need to move the catchError
into the switchMap
call as you want to "hide" the error from the switched observable already. This can be done simply by nesting it:
this.search$.pipe(
tap(() => this.pending = true),
switchMap(criteria => this._dealer.search(criteria)
.pipe(catchError(ErrorNotifierService.catchResponseErrorAsObservable))
)
).subscribe(…);
The problem with your code is that in your case switchMap
will switch to an observable emitting the error, which ends the subscription. We want to map this error to an emission before we switch to that observable so that the resulting stream never even sees an error.
You can find a runnable, online example of your code here and the fixed example here.
Upvotes: 1