In this example we gather up information from two different API endpoints, combine them and present them as one object to the subscriber.
Explanation:
- We create an observable that queries the 1st endpoint.
- With
mergeMap
operator we trigger query for the 2nd endpoint. The 2nd query depends on the results of the 1st query. - Finally we
combineLatest
the two observables into one that emits the combination of the two.
...
const postArray = this.getPosts();
const comments = postArray.pipe(
mergeMap(posts => this.http.get(`https://jsonplaceholder.typicode.com/posts/${posts[1].id}/comments`))
);
const latest = combineLatest (postArray, comments, (posts, cmnt) => {
return {a: posts, b: cmnt};
})
latest.subscribe(data => {
this.posts = data.a;
this.comment = data.b;
});
Note: We use RxJS 5.5 which now use the 'lettable' operators.