1

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

3
  • Yes, MergeMap is a good idea here Commented Jul 17, 2017 at 11:59
  • Thanks, the problem is that I cannot find how to iterate through users with mergeMap. Commented Jul 17, 2017 at 12:01
  • what is the problem you are facing? Commented Jul 17, 2017 at 12:10

1 Answer 1

3

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.

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

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.