[英]How can I read and bind data from this JSON to a Select dropdown in Angular 2+
This is what my JSON looks like: 这是我的JSON的样子:
{
"Stations": {
"44": {
"NAME": "Station 1",
"BRANCH_CD": "3",
"BRANCH": "Bay Branch"
},
"137": {
"NAME": "Station 2",
"BRANCH_CD": "5",
"BRANCH": "Beach Branch"
}
}
}
I would like to know if its possible to extract the "NAME" and "BRANCH" values from each "Station" and bind them to separate Select inputs [dropdowns] 我想知道是否有可能从每个“站”中提取“名称”和“分支”值并将它们绑定到单独的选择输入[下拉列表]
I am using Angular 4. Here is what I have: 我正在使用Angular4。这是我所拥有的:
this.apiService.getStations().subscribe(data => {
this.stationList = data.Stations;
}, err => {
this.errorFetchingStations = err;
console.log("Error getting list of stations " + err);
})
this.stationList
gives me an object of this format in the console: this.stationList
在控制台中给了我这种格式的对象:
{44:{NAME: "Name of station", BRANCH: "Name of branch"}}
{137:{NAME: "Name of station", BRANCH: "Name of branch"}}
and so on. 等等。
If I try to bind the stationList to my select like this, I get an error 如果我尝试像这样将stationList绑定到我的选择,则会出现错误
ERROR Error: Error trying to diff '[object Object]'. 错误错误:尝试与'[object Object]'进行比较时出错。 Only arrays and iterables are allowed
仅允许数组和可迭代
<select class="form-control">
<option *ngFor="let station of stationList" [value]="station.NAME">{{station.NAME}}</option>
</select>
You are having key value pair to the object instead ngFor expects an array so you should use the below code 您具有对象的键值对,而不是ngFor需要一个数组,因此应使用以下代码
this.apiService.getStations().subscribe(data => {
this.stationList = Object.values(data.Stations); // returns an array
}, err => {
this.errorFetchingStations = err;
console.log("Error getting list of stations " + err);
})
you should transform the stationList to array and you can use the Object.values(data.Stations), as the below. 您应该将stationList转换为数组,然后可以使用Object.values(data.Stations),如下所示。
this.apiService.getStations().subscribe(data => {
var stations = data.Stations;
this.stationList = Object.values(stations);
}, err => {
this.errorFetchingStations = err;
console.log("Error getting list of stations " + err);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.