在 Angular2 和 ionic 中读取 API 响应

Read API response in Angular2 & ionic

本文关键字:读取 API 响应 ionic Angular2      更新时间:2023-09-26

我已经成功地让它在 Angular2 中使用 http.get 从 API 请求数据。这是我的http.get

this.http.get('http://localhost:8001/v1/recent', {
      headers: headers
  })
  .map(res => res.text())
  .subscribe(
    data => console.log(data.total),
    () => console.log('API request complete')
  );

该 API 基于 Laravel,它将返回如下数据

{
   "total": 8,
   "per_page": 50,
   "current_page": 1,
   "last_page": 1,
   "next_page_url": null,
   "prev_page_url": null,
   "from": 1,
   "to": 8,
   "data": [
      {
         "id": 1,
         "name": "John Doe",
         "author": {
            "isBlocked": "0",
         }
      },
      {
         "id": 1,
         "name": "John Doe",
         "author": {
            "isBlocked": "0",
         }
      }
    ]
}

如何在 Angular2 中检索上面的 JSON 对象? 它都是嵌套数组?

console.log(data.total)上面是返回未定义的

您问题中的 json 格式不正确,您在 "isBlocked":"0" 之后有一个额外的逗号(在第 15 行和第 22 行)

"author": {
   "isBlocked": "0",
}

这将使它成为无效的 JSON。阻止 Angular 正确解析它。

另一个问题,您正在调用.map(res => res.text())它将响应正文转换为字符串而不是对象。如果你想把它作为一个javascript对象,.map(res => res.json())改用。

这是一个工作弹道