Angular4: HttpClient - many requests in succession

隐身守侯 提交于 2019-12-04 23:23:38

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;

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