首页 > 解决方案 > 如何使用 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 请求接收的数据数组。

标签: arraysjsonangulartypescriptobservable

解决方案


你不能.push到一个未初始化的数组。

尝试这样做:

userData = [];

推荐阅读