简体   繁体   English

Angular中根据页面大小多次调用API

[英]Multiple API calls based on page size in Angular

API call - getList() => returns 1000 numbers API 调用 - getList() => 返回 1000 个数字

  • Say 1,2,3...1000说 1,2,3...1000

Make 20 API calls by taking above top 20 results通过获取前 20 个以上的结果拨打 20 个 API 电话

I am trying to do something like this我正在尝试做这样的事情

this.http.get('urlService').mergeMap((ids: number[]) => this.getItems(ids.slice(0, 20))).
  subscribe(newsList => {
    this.dataRecieved.next(newsList);
  })

But its not working somehow但不知何故它不起作用

You could use RxJS forkJoin function to combine multiple HTTP requests.您可以使用 RxJS forkJoin function 组合多个 HTTP 请求。 It'll emit only when all the observables complete.它只会在所有可观察对象完成时发出。

this.http.get('urlService').pipe(
  switchMap((ids: number[]) => forkJoin(ids.slice(0, 20).map(id => this.getItems(id))))
).subscribe(newsList => {
  // newsList[0] - response from `this.getItems(1)`
  // newsList[1] - response from `this.getItems(2)`
  ...
  this.dataRecieved.next(newsList);
});

I am using Array map function to convert the list [1, 2, ..., 20] to a list of HTTP requests [this.getItems(1), this.getItems(2), ..., this.getItems(20)] .我正在使用数组map function 将列表[1, 2, ..., 20]转换为 HTTP 请求列表 [this.getItems [this.getItems(1), this.getItems(2), ..., this.getItems(20)]


However, beware that this will trigger 20 simultaneous HTTP calls.但是,请注意,这将同时触发 20 个 HTTP 调用。 Most browsers have a hard limit (Chrome - 6) on how many concurrent calls to the same domain could be made.大多数浏览器对可以对同一域进行多少次并发调用都有硬性限制(Chrome - 6)。 The recommended way to solve this limit issue is to use WebSockets or domain sharding.解决此限制问题的推荐方法是使用 WebSockets 或域分片。

As a workaround from front-end, you could use RxJS bufferCount operator with from function to control the maximum number of parallel requests made at a time.作为前端的解决方法,您可以使用 RxJS bufferCount运算符和from function 来控制一次发出的最大并行请求数。

this.http.get('urlService').pipe(
  switchMap((ids: number[]) => from(ids.slice(0, 20).map(id => this.getItems(id)))),
  bufferCount(6),                         // <-- adjust number of parallel requests here
  concatMap(buffer => forkJoin(buffer))
).subscribe(
  newsList => this.dataRecieved.next(newsList),
  error => // handle error
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM