Issue
I have a scenario where I want to call an API and, if returns 200, I want to call another API but I'm only interested in the response of the first API called. Something like this:
const http1$ = of('response 1');
// const http2$ = of('response 2');
const http2$ = throwError('response 2');
http1$.pipe(
switchMap((response1) => http2$.pipe(map(() => response1)))
).subscribe(response1 => {
// I need to get response 1 even if http2 fails which, in this case, won't work
console.log(response1);
});
The only solution that comes to my mind atm is having a subscribe to http2 in a tap or inside the subscribe of http1 but this is not a good practice.
Solution
If I understand the problem right, "piping" a catchError
into the map
operator should do the trick for you.
Something along these lines
http1$.pipe(
switchMap((response1) => http2$.pipe(
map(() => response1)).pipe(
catchError(() => of(response1))
)
)
).subscribe(response1 => {
// I need to get response 1 even if http2 fails which, in this case, won't work
console.log(response1);
});
EDIT AFTER THE COMMENT If instead you want to fire-and-forget http2$ after http1$ has returned, but are not interested at all in the result of http2$ (the forget part of fire-and-forget) and return immediately the response of http1$, then you may proceed like this
// first create a shared stream starting with http1$
const http1Shared$ = http1$.pipe(
share()
);
// then use the shared stream to create a new stream which will trigger http2$ as soon as http1$ returns
// the use of the shared stream is to make sure http1$ is only called once
// you can catch the error and ignore it using catchError(() => EMPTY)
// EMPTY is an observable that completes immediately without emitting any value and without erroring
const stream2$ = http1Shared$.pipe(
switchMap(() => http2$),
catchError(() => EMPTY),
);
// then subscribe to both streams - the first one will be used to process the response from http1$
// the second one will be used to trigger http2$ as soon as http1$ returns but will ignore its response
http1Shared$.subscribe(response1 => {
// I need to get response 1 even if http2 fails which, in this case, won't work
console.log(response1);
});
stream2$.subscribe();
Answered By - Picci
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.