AngularFire2在数组中嵌套了* ngFor数组...但是Firebase没有数组...? [英] AngularFire2 nested *ngFor Array within Array... but Firebase doesn't have arrays...?
问题描述
我正在使用AngularFire2,试图将列表从列表中取出. * ngFor中的嵌套* ngFor不会显示在视图中...
I'm using AngularFire2, trying to get lists out of lists. A nested *ngFor within an *ngFor doesn't show on the view...
app.componnent
app.componnent
...
constructor(private _af: AngularFire) {
this.lists = this._af.database.list(this._API_URL);
}
...
app.component.html
app.component.html
<div *ngFor="let list of lists | async">
{{sublist.name}}<br/> <!-- I can see you -->
<!--******* I can't see you **********-->
<div *ngFor="let rootword of list.rootwords">
{{rootword.word}} {{rootword.total}}
</div>
</div>
Firebase示例
Example of Firebase
maindb
|_list1
| |_name: 'List 1"
| |_rootwords
| |_apple
| | |_word: 'apple'
| | |_total: 4
| |
| |_banana
| | |_word: 'banana'
| | |_total: 2
| |_carpet
| | |_word: 'carpet'
| | |_total: 21
|
|_list2
|_name: "List 2"
|_rootwords
|_elephant
| |_word: 'elephant'
| |_total: 4
|_sloth
|_word: 'sloth
|_total: 5
如何使用firebase.list将ngFor嵌套在ngFor中? 我需要地图或过滤器吗? AngularFire2是否可以将内部对象转换为数组?
How do you nest an ngFor in an ngFor with firebase.list ?? Do I need to map or filter? Does AngularFire2 have a way to convert the inner object to an array?
感谢所有建议!
推荐答案
您可以使用rootwords对象="nofollow noreferrer"> map
运算符和 Array.prototype.reduce
,如下所示:
You can replace the rootwords
object with an array using the map
opererator and Array.prototype.reduce
, like this:
import 'rxjs/add/operator/map';
constructor(private _af: AngularFire) {
this.lists = this._af.database
.list(this._API_URL)
// Use map the map operator to replace each item in the list:
.map(list => list.map(item => ({
// Map to a new item with all of the item's properties:
...item,
// And replace the rootwords with an array:
rootwords: Object.keys(item.rootwords)
// Use reduce to build an array of values:
.reduce((acc, key) => [...acc, item.rootwords[key]], [])
})
));
}
或者,不使用传播语法:
Or, without the spread syntax:
import 'rxjs/add/operator/map';
constructor(private _af: AngularFire) {
this.lists = this._af.database
.list(this._API_URL)
.map(list => list.map(item => {
var copy = Object.assign({}, item);
copy.rootwords = Object.keys(item.rootwords).reduce((acc, key) => {
acc.push(item.rootwords[key]);
return acc;
}, []);
return copy;
}));
}
这篇关于AngularFire2在数组中嵌套了* ngFor数组...但是Firebase没有数组...?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!