Angular4: HttpClient - many requests in succession

2019-04-17 10:22发布

问题:

I have a http get request to get a list of some items from a feed. the feed API requires a page param, which is limited to 20. I would like to get first 60 instead, so I need to make 3 requests

requestOptions.params.set('page', 1);
this.http.get(environment.api+ '.feed.json', requestOptions)
requestOptions.params.set('page', 2);
this.http.get(environment.api+ '.feed.json', requestOptions)
requestOptions.params.set('page', 3);
this.http.get(environment.api+ '.feed.json', requestOptions)

what is the best way to deal with it to get an ordered list? I am not very fond of nesting

回答1:

Your service:

getPage(page) {
  /*init requestOptions*/
  requestOptions.params.set('page', page);
  return this.http
     .get(environment.api+ '.feed.json', requestOptions)
     .map(/*map your object to the expected one*/)
     .catch(/*catch any http exception*/);
}

Somewhere where you call the service

let allPages = [];

Observable.forkJoin(
  this.service.getPage(1);
  this.service.getPage(2);
  this.service.getPage(3);
).subscribe((respArray) =>{
   allPages = allPages.concat(respArray[0]);
   allPages = allPages.concat(respArray[1]);
   allPages = allPages.concat(respArray[2]);
});

Object.forkJoin will wait until all requests are completed and then you can build a single list with this results;



回答2:

There are many ways you can do this. I normally use Observable.forkjoin or Observable.merge

you can do this in below ways. Adjust the code little to run

// white a method which will call and get data and return observable
getData(pageNumber, requestOptions, environment) {
  requestOptions.params.set('page', pageNumber);
  return this.http.get(environment.api+ '.feed.json', requestOptions)
}

// make a fork-join/merge of all the observable and append the results

Observable.forkJoin(
   getData(pageNumber, requestOptions, environment);
   getData(pageNumber, requestOptions, environment);
   getData(pageNumber, requestOptions, environment);
).subscribe( (steream) => {
  //put some condition and all all those data
  result.push(stream);
});