-3

I need to make first HTTP request and get from response array of object. Then I need to make HTTP request for every object in array (probably in loop) to get extra info. All this inside Angular. I try with pipes but have some difficulties.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Darien Fawkes
  • 3,023
  • 7
  • 24
  • 35
  • 3
    What *"difficulties"*? Give a [mcve]. – jonrsharpe May 28 '19 at 07:40
  • I was able to build this:this.homeworld = this.http.get('/api/people/1').pipe( mergeMap(character => this.http.get(character.homeworld)) ); from this: this.http.get('/api/people/1').subscribe(character => { this.http.get(character.homeworld).subscribe(homeworld => { character.homeworld = homeworld; this.loadedCharacter = character; }); }); – Darien Fawkes May 28 '19 at 07:44
  • 2
    [Edit] the question. That doesn't seem to do anything with arrays. – jonrsharpe May 28 '19 at 07:45

2 Answers2

1

Basically you would use a mergeMap/flatMap for a nested api call by pulling the value out of the inner Observable and passing it back to the parent stream.

Like in the example in below answer if you had to make a nested call for fetching a User and then his preferences, you would use flatmap like below.

ngOnInit() {
    this.userService.getUser().pipe(
        tap(u => this.user = u),
        flatMap(u => this.userService.getPreferences(u.username))
      ).subscribe(p => this.preferences = p);
}

How to make nested Observable calls in Angular2

avinashkr
  • 512
  • 1
  • 5
  • 20
0

Your explanation is quite vague, and without a pseudocode example or an actual example of what you've tried to do, this is hard to answer.

But what I gather is that you need:

API call 1:

{ ids: [1, 2, 3] }

API call 2 takes an ID (api(1), api(2), api(3) etc.) and returns:

{ something: 'else', id: 1 }

In RxJS you would want to switchMap for every ID you get, so you can switch the subscription to a new Observable. If you want all of these to come in when they come in you would merge these. If you want them to come in predictably and in order you would concat them.

Basic example:

this.http.get<{id: number[]}>('api1').pipe(
   switchMap(ids => {
      return concat(ids.forEach(id => {
           return this.http.get<{ something: string, id: number}>('api2/' + id)
      })
   }).subscribe(console.log)
Bjorn 'Bjeaurn' S
  • 3,861
  • 2
  • 18
  • 29