Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 Observable.forkJoin with for loop

This is how i am working now:

getTwoObjectById(url1: string, id1: string, url2: string, id2): any{
  return Observable.forkJoin(
    this.http.get(url1 + `/${id1}`, this.jsonWebToken()).map(res => 
      res.json()),
    this.http.get(url2 + `/${id2}`, this.jsonWebToken()).map(res => 
      res.json())
  );
}

I want to prevent this kind of function with id1, url1, id2, url2, id3, url3...

I am trying to write a function that should take as params an Array of IDs and an Array of URLs. With Observable.forkJoin the for loop should execute each request getById to Backend-URL that are in Array. My problem is by the for loop

getObjectsById(ids: Array<string>, urls: Array<string>): Observable<any>{
  return Observable.forkJoin(

  for(let i = 0; i++; i<ids.length) {

     this.http.get(urls[i] + `/${ids[i]}`, this.jsonWebToken()).map(res => res.json());

  }

 )
}  

How can I do that?

like image 541
Manu Avatar asked Mar 08 '23 11:03

Manu


1 Answers

Try using this

inputObject = [1, 2, 3, 4];


getObjectsById() {
    let observableBatch = [];

    this.inputObject.forEach((key) => {
      observableBatch.push(this.http.get(url+key).map((res) => res.json()));
    });

    return Observable.forkJoin(observableBatch);
  }
like image 200
Rahul Singh Avatar answered Mar 16 '23 03:03

Rahul Singh