AngularFire2在Array中嵌套了* ngFor数组......但是Firebase没有数组......?

时间:2017-03-13 05:56:15

标签: firebase firebase-realtime-database nested angularfire2 ngfor

我正在使用AngularFire2,尝试从列表中获取列表。 * ngFor中的嵌套* ngFor未在视图中显示...

app.componnent

...
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

如何在ngfor with firebase.list中嵌套ngFor? 我需要映射还是过滤? AngularFire2有办法将内部对象转换为数组吗?

所有建议都赞赏!

1 个答案:

答案 0 :(得分:2)

您可以使用map opereratorArray.prototype.reduce将数组替换为rootwords对象,如下所示:

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;
    }));
}