Ionic 2 / Angular 2从数组中的对象获取数据 [英] Ionic 2 / Angular 2 Fetching Data from Object within Array
问题描述
我试图通过从 json 文件中提取数据,在 Ionic 2
中构建一个简单的手风琴。
我可以遍历类别和子类别项目来列出这些项目,但是一旦点击子类别,我就无法从子类别对象中获取数据并在详细页面上显示它(子类别标题)。我看了很多不同的教程/论坛,却找不到如何在任何地方这样做。
I am trying to build a simple accordion in Ionic 2
by pulling data from a json file.
I can iterate through the category and subcategories items to list those, however once a subcategory is clicked, I am not able to fetch the data from the subcategory object and display it (subcategory title) on a detail page. I have looked at many different tutorials/forums but couldn't find how to do this anywhere.
我想这不仅仅是路径问题,但我可能需要进一步迭代子类别对象?
I imagine it is not just an issue with the path but I might need to iterate through the subcategory objects further?
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});
}
}
detail.html
<ion-header>
<ion-navbar color="primary">
<ion-title>{{ item.subCategory.title }}</ion-title> // NOT WORKING
</ion-navbar>
</ion-header>
推荐答案
您需要发送 subItem
即每个子类别而不是 openDetails()
函数的项目。
You need to send the subItem
i.e. each subcategory and not the item to openDetails()
function.
<button (click)="openDetails(subItem)">{{ subItem.title }}</button><!-- here -->
在您的details.html中,
In your details.html,
你可以访问
<ion-title>{{ subItem.title }}</ion-title> <!-- make sure the parameter in ts file has name subItem. -->
这篇关于Ionic 2 / Angular 2从数组中的对象获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!