Reputation: 11
I have to make multiple http calls for my angular2 application. I first have to make one call, wait for the response, retrieve the next call's url from it and make the subsequent call. Similarly, my third call is based on 2nd call's response. I have to perform this operation until the response of a http call has no url to the next call. The problem here is I have no way of knowing how many calls i am going to make( It is solely dependent on the current response, if it has link to next call). Also I need to consolidate the response from all the calls.
Here is the response of each call.
{
"data": {
"page": 5,
"pageSize": 500,
"totalSize": 3000,
"entries": [],
"nextPage": {
"href": "http://someurl?
requestParam=someValue&page=1&pageSize=500",
"rel": null
}
}
}
I have to extract the value from nextPage attribute and make the http call until i get the the response where nextPage attribute is null like below.
{
"data": {
"page": 5,
"pageSize": 500,
"totalSize": 3000,
"entries": [],
"nextPage": null
}
}
Here is the code I am using to make one call. I am not sure how to chain these calls.
private load(extraUrlParam?: any) {
let me = this;
let url = me.getUrl(type, extraUrlParam, null);
me.pHttp.get(url, this.getHttpOptions())
.map((response: Response) => response.json())
.subscribe(
data => {
console.log("data received");
me.data = this.preProcessData(data);
me.dataSubject.next(this.data);
},
error => {
this.dataSubject.error(error);
me.handleError(error, url, type);
});
}
Any suggestions are greatly appreciated.
Upvotes: 1
Views: 498
Reputation: 17909
Use recursion. Here is an example. It will execute sequence and accumulate a result till a condition is met.
function getNext(acc, res) {
return res < 10 ?
Rx.Observable.of({acc: acc + ':' + (res+1), val: res+1})
.switchMap(({acc, val}) => getNext(acc, val)) :
Rx.Observable.of({acc:acc, val: 'done'});
}
Rx.Observable.of(0)
.switchMap(x => getNext(x, x))
.subscribe(({acc}) => console.log('result:', acc))
Upvotes: 1
Reputation: 5436
I don't know if this is the best solution. But what comes to mind is something recursive like @mast3rd3mon suggested:
Call loadData() once
private url:string;
private loadData(extraUrlParam?: any){
let me = this;
this.url = me.getUrl(type, extraUrlParam, null);
this.load(extraUrlParam);
}
private load(extraUrlParam?: any) {
let me = this;
me.pHttp.get(url, this.getHttpOptions())
.map((response: Response) => response.json())
.subscribe(
data => {
console.log("data received");
me.data = this.preProcessData(data);
me.dataSubject.next(this.data);
// CHANGE THE URL HERE
me.url = RECIEVED_URL;
me.load(extraUrlParam);
},
error => {
this.dataSubject.error(error);
me.handleError(error, url, type);
});
}
Upvotes: 0