Like mentioned above, a nice solution would be to catch an error INSIDE the switchMap()
call:
switchMap(() => {
return this.http.get(...).pipe(
catchError((error) => this.handleError(error)))
}),
However, if your pipe()
operator has many switchMap()
calls, and thus an error might be received in multiple cases, the best solution would be to subscribe again.
For example:
void subscribeData(): void {
data.pipe(
tap(() => this.isLoading = true),
switchMap(() => this.http.get(...).pipe(
catchError(err => {
// lot of copy-paste logic
})
)),
switchMap(() => this.http.get(...).pipe(
catchError(err => {
// lot of copy-paste logic
})
)),
switchMap(() => this.http.get(...).pipe(
catchError(err => {
// lot of copy-paste logic
})
)),
switchMap(() => this.http.get(...).pipe(
catchError(err => {
// lot of copy-paste logic
})
)),
switchMap(() => this.http.get(...).pipe(
catchError(err => {
// lot of copy-paste logic
})
)),
switchMap(() => this.http.get(...).pipe(
catchError(err => {
// lot of copy-paste logic
})
)),
switchMap(() => this.http.get(...).pipe(
catchError(err => {
// lot of copy-paste logic
})
)),
tap(() => this.isLoading = false, () => this.isLoading = false),
takeUntil(this.destroy)
).subscribe(data => {...})
);
You don't need to have the catchError(...)
and copy-paste the same logic for each time. The simpler solution would be to subscribe again on the (error) => {...}
callback in the subcribe(...)
call:
void subscribeData(): void {
data.pipe(
tap(() => this.isLoading = true),
switchMap(() => this.http.get(...)),
switchMap(() => this.http.get(...)),
switchMap(() => this.http.get(...)),
switchMap(() => this.http.get(...)),
switchMap(() => this.http.get(...)),
switchMap(() => this.http.get(...)),
switchMap(() => this.http.get(...)),
switchMap(() => this.http.get(...)),
switchMap(() => this.http.get(...)),
tap(() => this.isLoading = false, () => this.isLoading = false),
takeUntil(this.destroy)
).subscribe(data => {...}, err => {
//some other logic
// subscribe again
this.subscribeData(); // <--- subscribe again
});
}