我正在使用 AngularFire2,试图从列表中获取列表。 *ngFor 内的嵌套 *ngFor 不会显示在 View 上...
应用程序组件
...
constructor(private _af: AngularFire) {
this.lists = this._af.database.list(this._API_URL);
}
...
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 示例
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有办法将内部对象转换为数组吗?
感谢所有建议!
最佳答案
您可以使用 map
opererator 将 rootwords
对象替换为数组。和 Array.prototype.reduce
,像这样:
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]], [])
})
));
}
或者,没有扩展语法:
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;
}));
}
关于firebase - AngularFire2 在数组中嵌套 *ngFor 数组...但 Firebase 没有数组...?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42757379/