我正在尝试将Firebase中的嵌套数据显示到Ionic项目中。 我在firebase中有以下数据结构:
我的查询:
let dbRefLists = firebase.database().ref('lists/');
var self = this;
dbRefLists.on('value', (querySnapshot) => {
this.lists = Object.keys(querySnapshot.val()).map(key => querySnapshot.val()[key]);
querySnapshot.forEach((data) => {
var listItem = data.val().id;
dbRefLists.child(`${listItem}/listItems`).on('value', (snapshotVal) => {
if (snapshotVal.val() !== null) {
self.lists.listItems = Object.keys(snapshotVal.val()).map(key => snapshotVal.val()[key]);
}
})
return self.lists.listItems;
})
return lists;
});
我的HTML:
<ul>
<li *ngFor="let list of lists; let i=index" text-wrap (click)="toggleGroup(i)" [ngClass]="{active: isGroupShown(i)}">
<h2>
<span>{{list.title}}</span>
</h2>
<ul *ngIf="isGroupShown(i)">
<li *ngFor="let listItem of lists.listItems">
<span>{{listItem.title}}</span>
</li>
</ul>
</li>
</ul>
结果是我收到了所有列表(List1和List2)中的列表项,而不是仅在List1中:
我的错误在哪里?感谢
答案 0 :(得分:2)
如果您将数据库结构压扁如下:
排队将变得更加容易。 首先让我创建类,它们将位于Firebase服务文件中,如下所示:
export class myList {
listId: string
elClass: string;
title: string;
items?: myItem[];
constructor(listId: string,elClass: string,title: string, items?: myItem[]){
this.listId=listId;
this.elClass=elClass;
this.title=title;
if(items){
this.items = items;
}
}
}
export class myItem {
listId: string;
title: string;
constructor(listId: string,title: string){
this.listId=listId;
this.title=title;
}
}
获取数据:
data: myList[] = [];
onGetListsWithItems(){
let ref = firebase.database().ref('/');
ref.child('lists/').on('child_added', (snapshot)=>{
let list: myList = new myList(snapshot.key, snapshot.val().elClass, snapshot.val().title);
let items: myItem[] = [];
let listId = snapshot.key;
ref.child('listItems/')
.orderByChild('listId')
.equalTo(listId)
.on('child_added', (item)=>{
items.push(new myItem(item.val().listId, item.val().title));
});
list.items = items;
this.data.push(list);
});
}
这将为您提供(console.log数据):
[myList, myList]
0:{
elClass:"inActive",
listId:"randomlistId1",
title:"List1",
items: {
0:{
listId:"randomlistId1",
title:"Item2"},
1:{
listId:"randomlistId1",
title:"Item1"}
},
1:{
elClass:"inActive",
listId:"randomlistId2",
title:"List2",
items:{
0:{
listId:"randomlistId2",
title:"Item2"}
}
最后你可以用HTML显示它:
<ul>
<li *ngFor="let list of data">
<h3>{{list.title}}</h3>
<ul>
<li *ngFor="let item of list.items">
<p>{{item.title}}</p>
</li>
</ul>
</li>
</ul>
结果如下:
如果您对代码有任何意见或者您有任何问题,请告诉我。