1

我对 Angular 非常陌生,到目前为止,我对它的强大感到非常兴奋。我正在使用 angularfire2 库从 firebase (*.ts) 中检索两个单独的列表:

this.list1= this.db.list("list1").valueChanges();
this.list2= this.db.list("list2").valueChanges();

在使用 *ngFor 循环第一个列表时,我想使用 list1.val 作为获取 list2 值的键

(list2[list1.val].name).

在尝试不同的事情时,我遇到了很多不同的错误,但最突出的是这个错误:

TypeError: Cannot read property 'party' of undefined

这就是我的 *.html 文件目前的样子(正在尝试使用异步进行一些魔术):

<ion-row *ngFor="let item1 of list1| async">
  <ion-col>{{item1.val}}</ion-col>
  <!--different attempts-->
  <ion-col>{{(list2|async)[item1.val].name}}</ion-col>
  <ion-col>{{(list2[item1.val].name| async)}}</ion-col>
  </ion-col>
</ion-row>

我认为 ngFor 正在以某种方式改变 list1 的结构:

Observable<any[]>

到一个更易消耗的对象。没有它,我的 list2 对象实际上是不能被索引的东西,除非发生某种转换?帮助 :)

4

1 回答 1

1

所以我能够在这篇文章的帮助下解决这个问题:Nested Observables in Angular2 using AngularFire2 not rendering in view

诀窍是制作一个映射函数,将一个可观察的对象映射到我的第二个节点:

this.list1= this.db.list("list1").snapshotChanges().map(changes => {
  return changes.map(list1Obj => ({
    l1Key: list1Obj.payload.key,
    list2Obj: this.db.object('list2/' + list1Obj.payload.key).valueChanges()
  }));
});

然后,我能够像这样在 html 中显示它:

  <ion-row *ngFor="let item1 of list1| async">
    <ion-col>{{item1.l1Key}}</ion-col>
    <ion-col>{{((item1.list2Obj | async)?.name)}}</ion-col>
  </ion-row>
于 2017-11-17T20:15:51.120 回答