![](/img/trans.png)
[英]how to get selected value from Drop-down, if drop-down is binded with keys of json
[英]Retrieve values from JSON response, and create a drop-down
我正在尝试获取 JSON 文件中的每个值,但是当我运行 API 时,我得到[Object Object]
而不是 JSON 中的值。
这是我的 API 请求:
getAllvalues(): Observable<string[]> {
return this.http
.get<string[]>(this.Url + 'api');
}
我的组件.ts
this.ddvService.getAllvalues()
.subscribe(response => {
this.slots = response;
console.log (this.slots)
});
我的 JSON 响应示例:
[
{
"AB": "http:"
},
{
"DE": "http:"
},
{
"CE": "http:"
},
{
"HI": "http:"
}
]
如何获取 JSON 中的值,并为每个值创建一个下拉框?
您的示例 JSON 是一个非常糟糕的示例: JSON 中的数组中的每个 object 应该至少有一些匹配的键名。 在您的情况下,键是“AB”、“DE”、“CE”、“HI” - 都不同,这在现实生活中非常罕见。 更真实的 JSON 响应将具有匹配的键名,例如:
[
{
"id": "1",
"description": "Some description"
},
{
"id": "2",
"description": "Another description"
}
]
现在回答你的问题:
你得到[Object Object]
因为你试图使用整个 object 作为文字值。 相反,您应该访问 object 的各个键/值。 例如: console.log(slots[0].id)
- 这应该是 output 1
。
此外,如评论中所示,将Observable<string[]>
替换为Observable<any[]>
并将get<string[]>
替换为get<any[]>
。
要在 Angular 中创建下拉列表,您可以在组件模板中尝试此操作,假设您的slots
值是上面的 JSON:
<select *ngIf="slots" name="slots">
<option *ngFor="let slot of slots" value="slot.id">{{ slot.description }}</option>
</select>
此外,以可读形式将整个 object 打印到控制台,而不仅仅是console.log(this.slots);
, 你可以试试console.log(JSON.stringify(this.slots));
正如上面的评论中提到的,像你一样拥有 json 并不理想,我的假设是你可能想要记录键而不是值,因为数组中所有对象的值都是相同的。 在这种情况下,您可能想尝试这样的事情。 1. 添加任何[] 代替字符串[]。
2.添加嵌套for循环到console.log你的object数组。
getAllvalues(): Observable<string[]> {
return this.http
.get<any[]>(this.Url + 'api');
}
this.ddvService.getAllvalues()
.subscribe(response => {
this.slots = response;
for(let i in this.slots)
{
let currentObj = this.slots[i]; // example of first in array { AB : "http:"}
for ( let z in currentObj )
{
if(currentObj[z]=== "http:") // we are trying to find key instead value
{
console.log(z); // it will log AB, DE, CE, HI ..
}
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.