angular - 使用 Angular 的 GET 请求中出现错误 [object Object]
问题描述
我正在使用 Ionic 构建一个移动应用程序,该应用程序向服务器发送 GET 请求,接收项目列表作为响应并将它们显示在页面上。
home.ts 中的代码如下:
const url = <my_url>;
let day_id = <some_id>
this.response = this.httpClient.get(url);
this.response
.subscribe(res => {
this.items = res[day_id];
});
我应该得到以下结构的响应:
{day_id: [{"time": ..., "name": ...}, {...}, {...}]}
然后我遍历收到的项目以显示它们,如下所示:
<ion-list>
<button ion-item *ngFor="let item of items" (click)="itemTapped($event, item)">
{{item.time}}
<div class="item-note" item-end>
{{item.name}}
</div>
</button>
但不幸的是,当我运行该应用程序时,它会给出一些ERROR [object Object]
. 正如我所见,它发生在this.response.subscribe
.
我不知道这个问题可能与什么有关。因此,任何帮助将不胜感激。
解决方案
假设您将得到的响应是以下格式:
{day_id: [{"time": ..., "name": ...}, {...}, {...}], ...}
你想要一个所有对象的综合列表,你可以在你的块{ time: ..., name: ..., ... }
中做这个小改动:subscribe
this.response
.subscribe(res => {
console.log(res);
const finalArray = [];
Object.keys(res).forEach(key => finalArray.push(...res[key]));
this.items = finalArray;
});
day_id
应该是一个字符串。