In My Angular application, I have to call two API methods sequentially. If first API call returns 200 OK or Success then need to invoke second API method.
If first call is not successful then need to log error and should not call second method.
If first call is successful then need to invoke second API methods and if response is 200 OK or success then should return success.
If second call is not successful then need to log different error message.
import { switchMap } from 'rxjs/operators';
validateandSave(user: User) {
return this.utility.validate().pipe(
switchMap(data => {
this.result= data.status;
if(status == 'success')
// call second method
})
)
}
Here main thing is, if first call is failed then second API method should not be invoked.
In Google, could see solutions with switchMap, mergeMap, Pipe etc.. But I could not find a solution to handle error separately.
Can someone please share me sample code to handle this scenario.
This question gets asked a lot. There are a lot of ways of managing errors with RxJS streams. Here's one: it catches errors, logs them, and then completes silently without any errors to the final subscription.
Of course, often you want to do better than ignore your errors.
validateandSave(user: User) {
return this.utility.firstStream().pipe(
catchError(err => {
console.log("Error from first call: ", err);
return EMPTY;
}),
switchMap(data =>
data.result === something ?
this.utility.secondStream() :
EMPTY;
),
catchError(err => {
console.log("Error from second call: ", err);
return EMPTY;
})
)
}