【发布时间】:2018-06-13 09:42:08
【问题描述】:
我有以下 JSON 文件:
{
"fruites": [
{"id" :"f1", "name": "apple", "selected": "false"},
{"id": "f2" , "name":"orange", "selected": "false"}
]
}
Here is my JSON interface:
export interface FruitsType {
id: String;
name: String;
selected : String;
}
不确定这是否是一个正确的接口。
我想使用水果的名称作为复选框的值
要阅读此 JSON,我有以下服务:
getJSON (): Observable<JSON> {
return this.http.get<JSON>((this.configUrl))
}
}
在我的组件中,我有以下代码来读取获取 JSON 文件:
this.jsonService.getJSON().subscribe(response => {
console.log(response.fruites);
console.log(response.fruites[1].name);
console.log(response.fruites.length);
for (this.i = 0; this.i < response.fruites.length; this.i++) {
console.log("id" + response.fruites[this.i ].id);
console.log("name" + response.fruites[this.i].name);
console.log("selected" + response.fruites[this.i].selected);
}
})
在浏览器中我可以看到它可以工作,而在我运行 ng serve 的控制台中我看到以下错误:
src/app/componenets/home/home.component.ts(221,41):错误 TS2339:“JSON”类型上不存在属性“fruites”。
另一件事是我无法将它推送到数组中,我使用以下代码:
this.jsonArray.push(response.fruites[this.i].name )
AND
this.jsonArray.push(response.fruites)
AND
this.jsonArray.push(response)
所有返回未定义或什么都没有!
请咨询我。
【问题讨论】:
-
发布您的 JSON 类/接口
-
您是否收到了预期的响应?在 subscibe 方法里面?
-
@Sajeetharan 我现在做到了。如果这就是你的意思
-
因为错误表明您返回的 JSON 类型没有结果
-
是的。如下: (2) [{…}, {…}] 0: {id: "f1", name: "apple", selected: "false"} 1: {id: "f2", name: "orange" , selected: "false"} length: 2__proto__: Array(0) orange 2 id: f1 name: apple selected: false id: f2 name: orange selected: false