0

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

1
  • forkJoin create an unique observable. You has write bad the parenthesis: forkJoin(myIds.map((i:number)=>this.http.get('apicallwidth/'+i))).subscribe((res:any[])=>{console.log(res)}). In two steps: obs$=forkJoin(myIds.map((i:number)=>this.http.get('apicallwidth/'+i))); obs$.subscribe(...) Commented Jan 18, 2023 at 21:49

2 Answers 2

1

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)
})
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks @Ahmed Mostafa combineLatest works to get each and every response but can you update your solution to save them all into a single array.
it is already single array of response >>> pelase describe the shape that you want the result now [res1,res2,res3] tell me what shape you need and i will try my best to solve it
console.log gives me for using id: 1 and 2 >>>> [{user:'tom',id:1}] and [{user:'jerry',id:2}] instead I need it as [{user:'tom',id:1}, {user:'jerry',id:2}]
if you have teamViewer let us meet to check please
nothing to share anyway thanks. I'll try to figure it out
|
1

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)
    }
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.