gpt4 book ai didi

javascript - 读取 Angular2 和 ionic 中的 API 响应

转载 作者:行者123 更新时间:2023-12-03 07:05:55 26 4
gpt4 key购买 nike

我已经成功地在 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())

Here is a working plunker

关于javascript - 读取 Angular2 和 ionic 中的 API 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36827198/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com