我正在使用 ionic 4,并且尝试通过 http.get 使用 TransportAPI 获取 JSON 数组,但是,它们使用整数字符串作为我尝试获取的对象的键,然后有多个每个对象的数组,如下所示:
{
"departures": {
"25": [
{
"mode": "bus",
"line": "25",
"departure_time": "12:40"
},
{
"mode": "bus",
"line": "25",
"departure_time": "13:00",
}
],
"50": [
{
"mode": "bus",
"line": "50",
"departure_time": "12:46",
},
{
"mode": "bus",
"line": "50",
"departure_time": null,
},
{
"mode": "bus",
"line": "50",
"departure_time": "14:46",
}
]
}
}
此 JSON 数组存储在“testArray: any;”中实际获取它没有问题,因为我可以将其打印到控制台日志中。几个小时后我才发现你必须将数字键放入括号表示法即。 [“25”] 来访问这些,但是我不确定在使用 *ngFor 时如何解决这个问题,或者即使您愿意。这是我试图输出的粗略代码:
<div *ngFor="let bus of testArray.departures"> //this is where I'm not too sure
<ion-item-divider>
<ion-label> bus line: {{ bus.line }}</ion-label>
</ion-item-divider>
<ion-item *ngFor="let time of bus"> //no idea what I'm doing here either
{{ time.departure_time }}
</ion-item>
</div>
任何帮助将不胜感激!
编辑:这是我用来获取 JSON 文件的代码(缺少导入和组件等以节省空间:
export class BusesPage implements OnInit {
testArray: any;
constructor(private http: HttpClient) {}
fillTestArray(){
this.http.get('assets/test.JSON').subscribe(data => {
this.testArray = data;
console.log(this.testArray);
});
}
ngOnInit() {
this.fillTestArray();
}
}
最佳答案
如果这是您希望迭代的数据,则需要使用键值管道,因为这是一个对象。 *ngFor without 用于迭代数组。这将使您可以迭代该对象。
然后,您可以在没有键值管道的情况下迭代嵌套在对象内的数组。这应该显示您想要的数据。
<div *ngIf="testArray"> // checks testArray exists
<div *ngFor="let bus of testArray.departures | keyvalue">
<div *ngFor="let data of bus.value">
<ion-item-divider>
<ion-label> bus line: {{ data.mode }}</ion-label>
<ion-label> bus line: {{ data.line }}</ion-label>
<ion-label> bus line: {{ data.departure_time }}</ion-label>
</ion-item-divider>
</div>
</div>
</div>
关于html - 当键是整数字符串时,如何使用 *ng-For 在 ionic 中显示 JSON 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55751717/