我试图通过从 json 文件中提取数据来在Ionic 2
中构建一个简单的手风琴。我可以迭代类别和子类别项目列出这些项目,但是一旦单击 sub类别,我就无法从 subcategory 对象中获取数据并显示它(详细信息页面上的子类别标题)。我看过许多不同的教程/论坛,但找不到如何在任何地方做到这一点。
我认为这不仅是路径的问题,而且我可能需要进一步迭代子类别对象?
JSON
{
"results": [
{
"category": "Category 1",
"subCategory": [
{
"title": "subCategory 1.1",
"word": "hello"
},
{
"title": "subCategory 1.2",
"word": "hello"
}
]
},
{
"category": "Category 2",
"subCategory": [
{
"title": "subCategory 2.1",
"word": "hello"
},
{
"title": "subCategory 2.2",
"word": "hello"
}
]
}
]
}
home.html
<ion-header>
<ion-navbar color="primary">
<ion-title>Categories</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
<ion-list>
<ion-item *ngFor="let item of (items | async)?.results">
{{ item.category }}
<div *ngFor="let subItem of item.subCategory">
<button (click)="openDetails(item)">{{ subItem.title }}</button>
</div>
</ion-item>
</ion-list>
</ion-content>
home.ts
export class HomePage {
items: any;
subcategories: any;
constructor(public navCtrl: NavController, public http: Http) {
this.items = this.http.get("assets/data/results-data.json").map(res => res.json());
}
openDetails(item) {
this.navCtrl.push('FilmDetailsPage', {item: item});
}
}
详细信息。html
<ion-header>
<ion-navbar color="primary">
<ion-title>{{ item.subCategory.title }}</ion-title> // NOT WORKING
</ion-navbar>
</ion-header>
您需要发送 subItem
即,每个子类别,而不是项目到 openDetails()
函数。
<button (click)="openDetails(subItem)">{{ subItem.title }}</button><!-- here -->
在您的细节中。html,
您可以访问
<ion-title>{{ subItem.title }}</ion-title> <!-- make sure the parameter in ts file has name subItem. -->