I want to make an API call in a loop with an array of IDs and store the response of each API call into a variable as an array.
const myIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 19]
forkJoin(
myIds.map((i: number) =>
this.http.get('apicallwith/${i}')
.subscribe(res) => {
const allResponses = [...res];
console.log(allResponses) // always getting the response of my first ID
}
)
)
I tried forkJoin from what I understood and not sure where I'm doing wrong
CodePudding user response:
you have to use combineLatest
here is example
import { combineLatest } from 'rxjs';
const myIds = [1, 2, 3, 4, 5, 6, 7, 8, 9, 19]
combineLatest(myIds.map(id => this.http.get('apicallwith/${id}')))
.subscribe((values)=>{
console.log(values)
})
CodePudding user response:
The reason forkJoin
wasn't working for you is that you were calling subscribe
inside the map
, which means you were passing an array of Subscriptions instead of an array of Observables (I would think TS would warn you about that).
The following would work using forkJoin
:
forkJoin(myIds.map(i => this.http.get('apicallwith/${i}'))).subscribe(
res => {
const allResponses = [...res];
console.log(allResponses)
}
);