【问题标题】:List in Ionic 3 with Firebase DB使用 Firebase DB 在 Ionic 3 中列出
【发布时间】:2018-09-29 03:45:34
【问题描述】:

我正在使用这样的 Firebase 数据库:

{
"rootList" : {
  "list_1" : {
    "guestsList" : {
      "item_1_1" : {
        "name" : "xxxxx",
        "surname" : "yyyyy"
      }
    },
    "hostName" : "Host_1"
  },
  "list_2" : {
    "guestsList" : {
      "item_2_1" : {
        "name" : "xxxx",
        "surname" : "yyyy"
      },
      "item_2_2" : {
        "name" : "xxx",
        "surname" : "yyy"
      }
    },
    "hostName" : "Host_2"
  },
  "list_3" : {
    "guestsList" : {
      "item_3_1" : {
        "name" : "xxyy",
        "surname" : "yyxx"
      },
      "item_3_2" : {
        "name" : "xyxy",
        "surname" : "yxyx"
      },
      "item_3_3" : {
        "name" : "xyyx",
        "surname" : "yxxy"
      },
      "item_3_4" : {
        "name" : "yxxy",
        "surname" : "xyyx"
      }
    },
    "hostName" : "Host_3"
  }
}
}

我通过 AngularFireDatabaseAngularFireList 类检索数据:

this.hostsDBList = this.aFDatabase.list('/rootList');
this.hostsList = this.hostsDBList.valueChanges();

在我的 html 中,我有:

<ion-content padding>
  <ion-list *ngFor="let list of hostsList | async">
    <ion-list-header>
      {{ list.hostName }}
    </ion-list-header>

    <ion-item *ngFor="let item of list.guestsList">
      {{ item.name }}
    </ion-item>
  </ion-list>
</ion-content>

标题比较容易,但它在第二个项目列表上给了我一个错误。 我不明白我是否也必须为每个子列表关联一个Observable。错误是 我尝试在*ngFor 中添加async 管道,如下所示:

*ngFor="let item of list.guestsList | async"

但它给了我另一个错误

它似乎无法在那种类型的对象上循环。我真的不明白如何从 Firebase 列表循环到子列表。有什么帮助吗?

【问题讨论】:

    标签: angular firebase ionic-framework ionic3 angularfire2


    【解决方案1】:

    我知道这有点晚了,但错误告诉你它为什么不起作用。 guestsList 不是数组,它是一个对象,因此你不能遍历它。

    您需要做的是使用自定义管道来使用Object.values() 像这样返回其属性值的数组

    import { PipeTransform, Pipe } from '@angular/core';
    
    @Pipe({name: 'values'})
    export class ValuesPipe implements PipeTransform {
      transform(object, args:string[]) : any {
        return Object.values(object);
      }
    }
    
    <ion-content padding>
      <ion-list *ngFor="let list of hostsList | async">
        <ion-list-header>
          {{ list.hostName }}
        </ion-list-header>
    
        <ion-item *ngFor="let item of list.guestsList | values">
          {{ item.name }}
        </ion-item>
      </ion-list>
    </ion-content>
    

    或者您可以将 guestsList 更改为数组,那么您甚至不需要自定义管道,但您会丢失 "item_X_X"

    "guestsList" : [
      {
        "name" : "xxxx",
        "surname" : "yyyy"
      },
      {
        "name" : "xxx",
        "surname" : "yyy"
      }
    },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      • 2018-02-19
      • 1970-01-01
      • 2019-10-11
      相关资源
      最近更新 更多