AngularFire2 вложил * ngFor Array в массив, но в Firebase нет массивов?

Я использую AngularFire2, пытаясь получить списки из списков. Вложенный *ngFor внутри *ngFor не отображается в представлении...

приложение.компонент

...
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 в ngFor с помощью firebase.list?? Нужно ли отображать или фильтровать? Есть ли у AngularFire2 способ преобразовать внутренний объект в массив?

Все предложения оценены!


person Craig O. Curtis    schedule 13.03.2017    source источник


Ответы (1)


Вы можете заменить объект rootwords массивом, используя map оператор и 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;
    }));
}
person cartant    schedule 13.03.2017
comment
Закомментировано второе | асинхронно, теперь ошибка — ожидается присвоение свойства. вызвано еще ... пунктом - person Craig O. Curtis; 14.03.2017
comment
Какую версию TypeScript вы используете? - person cartant; 14.03.2017
comment
Типскрипт v2.1.1 - person Craig O. Curtis; 14.03.2017
comment
Если я вручную добавлю ключи элемента, он сработает и удалит внутренний | асинхронный канал. - person Craig O. Curtis; 14.03.2017
comment
Синтаксис распространения должен быть действителен для версии 2.1, см. Расширение и отдых объекта. В любом случае, я добавил нераспространяемую версию. - person cartant; 14.03.2017
comment
Жаль, что оператор спреда почему-то не работает. Было бы очень элегантное решение... - person Craig O. Curtis; 14.03.2017