arrays - 如何使用 Angular 中的 observables 在 API http 请求的所有页面中获取数据?
问题描述
我正在向 API 发出 http.get 请求以获取数据。API 使用分页并包含 30 个条目/页。它还提供有关下一页和最后一页的信息以及响应标头链接中的相应链接(如果适用,还包括上一页和第一页)。
Link 标头包含分页信息:
<https://api.example.com/user?page=2>; rel="next",
<https://api.example.com/user?page=10>; rel="last"
response.body 中的 JSON 对象
[
{
userId: 1,
name: 'John',
created_at: "2015-10-13T03:10:43Z",
},
{
userId: 2,
name: 'Jane',
created_at: "2019-02-15T13:37:03Z",
}
....
]
我正在使用 angular 6 并尝试通过随后的 http.get 调用来积累数据。我曾尝试对后续数据使用数组方法 push()。但是由于 typeof resp.body 是 object 它不起作用。
userData: any[];
getData(url: string) {
this.http.get(url, {observe: 'response'});
.subscribe((resp) => {
this.userData.push(resp.body);
}
错误消息:TypeError:无法读取未定义的属性“推送”
userData 应该包含从可迭代的 http.get 请求接收的数据数组。
解决方案
你不能.push
到一个未初始化的数组。
尝试这样做:
userData = [];
推荐阅读
- python - 当我将 += 放入字典而不是 = 时出错的原因
- regex - 正则表达式:重用匹配结果以获得相同输出的另一个匹配?
- javascript - 如何判断 KeyboardEvent.key 是可打印字符还是控制字符?
- sass - 即使值存在,index() 函数也会返回 null
- python - 如何使用 setuptools 访问所有安装和分发案例中的数据文件?
- powershell - PowerShell:将 IP 地址转换为子网
- android - 关于 Kotlin 中的密封类,哪一个是正确的?
- java - 如何使用 UTC 和 CDT 时区传递 DateTime
- r - R 在 Lime 上解释 - 存储在“object”和“newdata”中的功能名称不同
- python - python什么时候决定一个名字是本地的还是对全局变量的引用?