I have 2 api calls which i want to send one after the other. I need a response of the 1st one to send the 2nd api request, but i also need the data from first call. Looks like switchMap is the way to go, atm it looks like this:
this.apiCall1().pipe(switchMap(res1 => this.apiCall2(res.data))).subscribe(res => ...)
but i need to assign the res1.differentData to a variable which seems impossible with switchMap. Or maybe im just missing some syntax.
CodePudding user response:
I suggest you to just reemit the value coming from apiCall1()
and use forkJoin
to get both values at the end:
this.apiCall1().pipe(
switchMap(res => forkJoin(
[of(res), this.apiCall2(res)]
))).subscribe(console.log)
this way you receive an array containing two elements (the results of both calls) at the end.
CodePudding user response:
You can also use map to the inner call to include all or part of the response from outer (usually used in a typical element details)
this.apiCall1().pipe(
switchMap(res1 => this.apiCall2(res1).pipe(
map(res2=>({res1:res1,res2:res2})))
)
CodePudding user response:
Without running the code myself, here is my take.
Possibly break-out your callback function:
let res1Stored;
this
.apiCall1()
.pipe(switchMap(res1 => {
res1Stored = res1.differentData;
return this.apiCall2(res.data);
}))
.subscribe(res => ...)
Hope this helps.