firebase - AngularFire2 在数组中嵌套 *ngFor 数组...但 Firebase 没有数组...?

标签 firebase firebase-realtime-database nested angularfire2 ngfor

我正在使用 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 opereratorrootwords 对象替换为数组。和 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/

相关文章:

firebase - 是否可以向 Firebase 默认 'session_start' 事件添加参数?

javascript - 两个可观察量之间的差异

android - 通过复制一些数据 android 重新创建一个 firebase 对象

android - 在不使用 ListView 的情况下从 Firebase 检索数据库并设置为 TexView?

r - 在 R 中的不同列上应用多个 if-else 条件

angular - 获取 Firestore 的 UID 引用

javascript - 我怎样才能将数据添加到firebase数据库中

java - 如何通过匹配 userType 和 android 中的验证状态来获取列表?

c - 嵌套结构的成员以某种方式附加到结构的前一个成员

syntax - PlantUML:带有文本的嵌套组件可能吗?