【问题标题】:Using ngFor item as key in an Observable list使用 ngFor 项目作为 Observable 列表中的键
【发布时间】:2017-11-16 08:35:29
【问题描述】:

我对 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 对象实际上是不能被索引的东西,除非发生某种转换?帮助:)

【问题讨论】:

    标签: angular typescript angularfire angularfire2 angularfire5


    【解决方案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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-18
      • 2018-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-26
      • 1970-01-01
      相关资源
      最近更新 更多