【发布时间】:2018-06-11 10:38:12
【问题描述】:
我需要在我的 Ionic List 中解析嵌套的 JSON。 我需要这样的东西
我正在使用 IONIC 和 Angular 4。
我的 JSON 格式是:
{
"result": {
"engineering": [{
"name": "Tamil Nadu",
"colleges": {
"list": [{
"id": "1",
"title": "wdwd"
}, {
"id": "2",
"title": "titlealsadasbum2"
}]
}
}, {
"name": "Kerala",
"colleges": {
"list": [{
"id": "3",
"title": "titleqqwalbum2"
}, {
"id": "4",
"title": "titleaasalbum2"
}]
}
}],
"medicine": [{
"name": "Tamil Nadu",
"colleges": {
"list": [{
"id": "1",
"title": "med-wdwd"
}, {
"id": "2",
"title": "med-titlealsadasbum2"
}]
}
}, {
"name": "Kerala",
"colleges": {
"list": [{
"id": "3",
"title": "med-titleqqwalbum2"
}, {
"id": "4",
"title": "med-titleaasalbum2"
}]
}
}]
}
}
列表:
<ion-list padding>
<ion-list-header color="primary">TamilNadu</ion-list-header>
<ion-item>VIT UNIVERSITY CHENNAI </ion-item>
<ion-item>SRM UNIVERSITYCHENNAI</ion-item>
<ion-item>VELTECH UNIVERSITY</ion-item>
<ion-list-header> Kerala</ion-list-header>
<ion-item>HINDUSTAN UNIVERSITY</ion-item>
<ion-item>SRM UNIVERSITYCHENNAI</ion-item>
<ion-item>VELTECH UNIVERSITY</ion-item>
<ion-list-header> Karnataka</ion-list-header>
<ion-item>VIT UNIVERSITY CHENNAI </ion-item>
<ion-item>SRM UNIVERSITYCHENNAI</ion-item>
<ion-item>VELTECH UNIVERSITY</ion-item>
<ion-list-header>Andra Pradesh</ion-list-header>
<ion-item>VIT UNIVERSITY CHENNAI </ion-item>
<ion-item>SRM UNIVERSITYCHENNAI</ion-item>
<ion-item>VELTECH UNIVERSITY</ion-item>
</ion-list>
我正在使用函数获取 json:
getIndianCollegeSearchData() {
this.showLoader();
this.apiService.getCollegeData().then((result) => {
console.log(result);
this.loading.dismiss();
this.searchResults = result
this.items = Object.keys(this.searchResults.result);
}, (err) => {
this.loading.dismiss();
console.log(err);
});
在 API 控制器中:
getCollegeData(){
return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('Authorization', this.authService.token);
this.http.get('http://13.126.17.194/colleges.php')
.map(res => res.json())
.subscribe(data => {
resolve(data);
}, (err) => {
reject(err);
});
});
}
如何在 Angular 中循环遍历这个 JSON?由于密钥本身是要打印的文本,所以我一直在解析这个 JSON。
我试过这个方法:
<ion-list-header color="primary" *ngFor="let key of items">{{key}}</ion-list-header>
未捕获(承诺中):TypeError:无法读取属性“结果” 未定义类型错误:无法读取未定义的属性“结果”
更新: 我添加了如下所述的对象。但是我怎样才能在关键工程中获得价值呢?
更新
正如 @JB Nizet 和 @Sajeetharan 所述,我将代码更改为 HttpClient,我在控制台中获得了响应 json。但是,当我将代码添加到 @Sajeetharan 提到的 html 时,我得到了错误:
ERROR 错误:未捕获(承诺中):TypeError:无法读取属性 未定义类型错误的“结果”:无法读取属性“结果” 不明确的 在 Object.eval [as updateDirectives] (IndianstudiesPage.html:24)
【问题讨论】:
-
Object.keys(this.searchResults.result)。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…。在您使用它的同时,学习和使用 HttpClient。 Http 服务已弃用。并学习 observables。将 observables 包装成 Promise 是很笨拙的。至少使用 toPromise() 运算符。 -
@JBNizet。我需要在哪里添加此代码?我正在使用 ng repeat 来填充列表。
-
无论您想在哪里访问结果对象的键。您的视图应该适用于适合它必须做的事情的模型。因此,让您的服务或组件将您从服务器获取的数据转换为视图可用的格式。
-
我认为 ng-repeat 适用于 angularJs 而不是 Angular。谁能解释一下?
-
@Melchia 是。不知道为什么 OP 尝试使用 ng-repeat 而不是 *ngFor。但那是另一回事了。