Angular4: HttpClient - many requests in succession

血红的双手。 提交于 2019-12-06 17:09:13

问题


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);
});


来源:https://stackoverflow.com/questions/45798178/angular4-httpclient-many-requests-in-succession

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!