简体   繁体   English

如何在Angular2服务中进行递归http调用以预取数据?

[英]How to make recursive http calls within an Angular2 service to prefetch data?

I've got an Angular service which fetches records from an open API. 我有一个Angular服务,可以从开放的API中获取记录。 The API limits me to fetching 100 records at a time and I won't know how many records there are to fetch until I retrieve the first batch. 该API将我限制为一次只能提取100条记录,直到我检索到第一批之前,我才知道要提取多少条记录。

The format of the API response looks like this: API响应的格式如下:

{
    "offset": 0,
    "limit": 100,
    "total": 140,
    "count": 100,
    "results": []
}

I don't know how many calls I need to make to the API until after I fetch the first page and get the "total" value from the response. 在获取首页并从响应中获取"total"值之前,我不知道需要对API进行多少次调用。

Any idea how to accomplish this? 任何想法如何做到这一点?

Thanks! 谢谢!

Not angular an specific problem, so no (real) code here. 没有具体的问题,所以这里没有(真实的)代码。

In any language; 用任何语言; you can do something like this: (ie call the getData function from the function that receives the data) 您可以执行以下操作:(即从接收数据的函数中调用getData函数)

var limit = 100;
var offset = 0;

function getData(offset) {
 someHTTPcall('http://...?offset='+offset)
 mapData(response)
}

function mapData(result) {
 myData.push(response.results)
 if (myData.length < response.total) {
   getData(myData.lenght +1)
 }
}

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

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