Reputation: 1151
I have a service (singleton) in angular that exposes an rxjs Subject as an observable. A component subscribes to the observable. When an error occurs in the observable, the component gets the error and displays it. However, if the user navigates away from the component, then navigates back, immediately the error is thrown again.
see https://stackblitz.com/edit/angular-nboawu
Upvotes: 1
Views: 445
Reputation: 2947
When you use Subject.error
, the Subject gets stopped and nothing happens to it afterwards, so you shouldn't use that.
That will fix your issue, besides as a suggestion catch the api errors yourself and process them as you wish. For example, you might store them somewhere or you might use Sentry.io (Sentry has free tier and works well with Angular).
For example:
this.api.getData().pipe(
catchError(error => this.doSomethingWithError(error)),
);
Upvotes: 0
Reputation: 421
This is actually the behavior of Subjects (and also Observables) in general. If there is an error happening this stream ends. Therefore it is pretty uncommon to emit an error in a Subject especially when you use it for statemanagement in angular applications. The error channel is also rather used for technical errors that happens inside your observable, for "error scenarios" I'd rather use the next channel but emit a complex object there, maybe something like
export interface SearchQueryResult {
data: SOMETHING,
error: any
}
Upvotes: 1