bidou88
bidou88

Reputation: 694

Angular - Nested API calls with iteration

Is there a better way to achieve this (getting all users with their photos) :

this.authHttp.get(this.ApiUrl+'users')
.map(res => res.json())
    .subscribe(users => {
        for (let user of users) {
            this.authHttp.get(this.ApiUrl+'users/'+user.id+'/photos')
            .map(res => res.json())
            .subscribe(photos => {
                user['photos'] = photos;
                this.items.push(user);
            })
        }
    });

Maybe using mergeMap ?

Thank you for your advice

Julien

Upvotes: 1

Views: 97

Answers (1)

Mark van Straten
Mark van Straten

Reputation: 9425

I'm assuming that res.json() is a sync call returning the json as object so you can chain on it:

this.authHttp.get(this.ApiUrl+'users')
.mergeMap(res = res.json().users)
.mergeMap(
  user => this.authHttp.get(this.ApiUrl+'users/'+user.id+'/photos'),
  (user, photosRes) => { 
    user['photos'] = photosRes.json(); 
    return user; 
   }
)
.subscribe(user => this.items.push(user));

This code example uses the mergeMap overload which takes a mapFunc(outer,inner) so you have access to both and can merge them together as you see fit.

Upvotes: 3

Related Questions