Reputation: 2217
I would like to make two consecutive http requests in an Angular 2 app where the result from the first ajax call is used in a subsequent set of ajax calls. I'm struggling to understand how to structure it.
The purpose of this arrangement is that the subsequent ajax calls obtain data for the purpose of adding detail (new properties) to the set of objects obtained in the first call.
I realize this is the ajax version of a 1+N problem however, I have limited control over the design.
The pseudo code below is (a function body) along the lines of what I think I need, but there's probably a cleaner way.
let finalObservable = Observable.create<viewModel>();
var firstAjax = this._http.request(url1, options)
.map((rs)=>rs.json());
firstAjax.subscribe((d)=>{
// d is an array of plain js objects
let secondAjax: Observable<any>[];
d.each((item, index)=>{
// roll item properties and index into url2s query string
secondAjax.push(_http.request(url2, options);
});
// assumption is I can pass an array of observables into forkJoin
Observable.forkJoin(secondAjax)
.subscribe((allRs)=>{
allRs.each((rs, index)=>{
d[index].newProperty = rs.text()
});
// give a value to the final observable
finalObservable.publish(d);
});
});
// Observable does not have a value yet, but will get one when the code
// above runs.
return finalObservable;
Not sure about ".publish". I'm trying to give an observable a value once I know what it is, which is sometime later than when I created the observable.
Upvotes: 1
Views: 645
Reputation: 39248
The way to chain requests in rx is via flatMap
Here is a simple example:
his.http.get('./customer.json').map((res: Response) => {
return res.json();
})
.flatMap((customer) => this.http.get(customer.contractUrl)).map((res: Response) => res.json())
.subscribe(res => this.contract = res);
Here is more detail and a demo as well:http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http
Upvotes: 1