I want to make 3 http calls which returns a boolean value.
What I want is to make the next call only if the result of the previos call is true
IE:
call1() -> if false, stop, if true:
call2() -> if false, stop, if true:
call3()
now read results in a way that indicates which call returned false if so.
my first attemp with switchMap:
this.call1()
.pipe(
switchMap((r1) => (r1 ? this.call2() : of(false))),
switchMap((r2) => (r2 ? this.call3() : of(false)))
)
.subscribe((r) => {
console.log('inside subscribe:', r);
});
the problem here that now inside the subscribe I get:
'inside subscribe:' false
and I can't know if the false result is from call1,2 or 3.
so my solution is to save the results in external array, like so:
// seriel execution with switchMap, we can use each result to the next call
// + save all results
const results = [false, false, false];
this.call1()
.pipe(
// save stage1 result
tap(r1 => results[0] = r1),
// if true, make call2, else return false
switchMap((r1) => (r1 ? this.call2() : of(false))),
// save stage2 result
tap(r2 => results[1] = r2),
// if true, make call3, else return false
switchMap((r2) => (r2 ? this.call3() : of(false))),
// save stage3 result
tap(r3 => results[2] = r3),
)
.subscribe((r) => {
console.log('inside subscribe:', r); // r is the latest value results[2]
console.log('all results:', results) // array of all stages [true,false,false]
});
}
and it seems to work, but maybe there is another way without external work? only with rxjs operators?
StackBlitz link:
https://stackblitz.com/edit/angular-rxjs-playground-zjnh7u?devtoolsheight=33&file=app/app.component.ts