-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.

3
  • 3
    What "difficulties"? Give a minimal reproducible example. Commented May 28, 2019 at 7: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; }); }); Commented May 28, 2019 at 7:44
  • 2
    Edit the question. That doesn't seem to do anything with arrays. Commented May 28, 2019 at 7:45

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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)

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.