3

Say I have two API calls that return JSON:

rows:

{
  {"row": 1, detailId: "a"}
  {"row": 2, detailId: "b"}
}

rowDetails:

{
  details: { this row details } 
}

I need to get rows, then loop through each row object getting the detailId to make another call to rowDetails, and attach the details to the row object. The final structure needs to be emitted like so:

{
  {"row": 1, "detailId": a, "details": { row details}}
  {"row": 2, "detailId": b, "details": { row details}}
}

In angular 1 I would use q.allSettled to wait for all the calls to finish.

I'm trying to do this the observable way and I am struggling conceptually and practically. I don't get how you are supposed to actually emit a merged "stream" as the final product.

I've tried roughly:

 this.http
     .get('rows')
     .map(res => res.json())
     .flatMap(group => this.http.get('rowDetails' + detailId))
     .map(res => res.json()).
     .subscribe(res => console.log(res))

Subscribe just emits the rowDetails call. How do I iterate through each object in the rows call and take that detailId for another call while merging the results for the final product? Any help would be greatly appreciated.

4
  • Does your second get actually depend on the result of the first? If not Observable.combineLatest seems like the best bet. Commented May 12, 2017 at 21:47
  • Yes it does, it needs the detailId from each row object to make a call to get the row details for that specific row Commented May 12, 2017 at 21:50
  • So you want to split out one call for each result of the first call then join all the results back together? Commented May 12, 2017 at 21:51
  • Yes I believe so Commented May 12, 2017 at 21:52

1 Answer 1

3

You need to take each item, create an HTTP request and after this inner request completes then propagate the updated item further.

this.http
    .get('rows')
    .map(res => res.json())
    .flatMap(group => this.http.get('rowDetails' + group.detailId)
        .map(res => {
            group.details = res.json();
            return group;
        })
    )
    .subscribe(res => console.log(res))

Notice that I'm actually returning group from the inner map. There are obviously many ways to approach this but I think this is the easiest one.

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.