-2

I'm having a problem with this code. I'm trying to collect extra details from a secondary endpoint that relates to the id in the returned collection from the first get. Can someone help on how to get the actual data out as its returning an array of observables. Thank you

this.http.get(`${this.apiUrl}/cinemas/location/cardiff`).pipe(
  map((data: any) => data.cinemas),
  map((cinemalist) => {
    return cinemalist.map(value => <Observable<any>>this.http.get(`https://api.cinelist.co.uk/get/cinema/${value.id}`));
  })
).subscribe(results => {
  console.log(results);
});
Wandrille
  • 6,267
  • 3
  • 20
  • 43
lee
  • 11
  • 2
  • Check [this](https://stackoverflow.com/questions/36984059/rxjs-array-of-observable-to-array) out – ukn Mar 15 '19 at 14:20

2 Answers2

4

Instead of a map, you can do a switchMap with a forkJoin:

this.http.get(`${this.apiUrl}/cinemas/location/cardiff`).pipe(
  map((data: any) => data.cinemas),
  switchMap((cinemas) => forkJoin(cinemas.map(value => <Observable<any>>this.http.get(`https://api.cinelist.co.uk/get/cinema/${value.id}`));
  }))
).subscribe(results => {
  console.log(results);
});

If you want to keep the value, you can try something like that:

this.http.get(`${this.apiUrl}/cinemas/location/cardiff`).pipe(
  map((data: any) => data.cinemas),
  switchMap((cinemas) => forkJoin(cinemas.map(value => <Observable<any>>this.http.get(`https://api.cinelist.co.uk/get/cinema/${value.id}`))
    .pipe(map(cinema => {...cinema,value}))
  }))
).subscribe(results => {
  console.log(results);
});
Wandrille
  • 6,267
  • 3
  • 20
  • 43
  • So it turns out i need to keep the original value held for each cinema ( value ). How would i create a result that combined both the original value in addition to the results of the get in the subquery? – lee Mar 15 '19 at 19:13
  • this.http.get(`https://api.cinelist.co.uk/search/cinemas/location/${town}`).pipe( map((data: any) => data.cinemas), switchMap((cinemas) => forkJoin( cinemas.map(value => >this.http.get(`https://api.cinelist.co.uk/get/cinema/${value.id}`)) ) ) ).subscribe(x => { console.log(x); }); – lee Mar 15 '19 at 19:45
  • adding the pipe freaks it out completely? – lee Mar 15 '19 at 19:45
  • I don't know, I haven't test it, sorry. – Wandrille Mar 15 '19 at 19:48
0
this.http.get(`https://api.cinelist.co.uk/search/cinemas/location/${town}`).pipe(
      map((data: any) => data.cinemas),
      flatMap((cinemas) =>
        forkJoin(
          cinemas.map(value => {
            return this.http.get(`https://api.cinelist.co.uk/get/cinema/${value.id}`).pipe(
              map((result: any) => {
                return { ...result, ...value };
              }));
          })
        )
      )
    ).subscribe(x => {
      console.log(x);
    });
lee
  • 11
  • 2