如果你像这样扁平化你的数据库结构:
排队将变得更加容易。
首先让我创建类,它们将位于 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>
结果如下:
如果您需要对代码进行任何评论,请告诉我,否则您会有任何疑问。
附:您可以在此处阅读有关扁平化数据库的信息new docs https://firebase.google.com/docs/database/web/structure-data?authuser=0和这里old docs https://www.firebase.com/docs/web/guide/structuring-data.html