【问题标题】:Stepping through objects returned from Firebase遍历从 Firebase 返回的对象
【发布时间】:2017-05-10 10:40:18
【问题描述】:

我在 Google Firebase 中存储了一个对象列表。我想处理每个对象并将它们存储在一个数组中:

firebase.database().ref('trainingsets').once('value')
            .then((snapshot) => {

                var trainingSets: TrainingSet[] = [];
                console.log(snapshot.val());   // Console 1

                snapshot.forEach((child) => {
                    console.log("child=" + child);  // Console 2
                    trainingSets.push(child);
                });

                console.log(trainingSets);  // Console 3

                this.trainingSets = trainingSets;
                this.trainingSetsChanged.next(this.trainingSets.slice());

            });

TrainingSet 是反映 Firebase 中存储的每个对象的模型:

export class TrainingSet {

    /**
     * Unique Identifier of this set
     */
    id:number;

    name:string;
    type: string;
    description: string;

}

我的数据已成功检索。在评论控制台 1 我看到一个对象,它有两个包含我的数据的子对象。然而,在控制台 2 中,我只得到空对象,而在控制台 3 中,我有一个包含正确数量元素的数组,但元素的标题为“V”,其中包含一堆奇怪的子项。我不确定那些实际上是什么。

谁能告诉我最好的方法是什么?我真的不需要一个数组,如果我可以正确地遍历对象树,我可能就可以使用它。

【问题讨论】:

    标签: typescript firebase firebase-realtime-database


    【解决方案1】:

    我在这里找到了我的解决方案:https://firebase.google.com/docs/database/web/lists-of-data#listen_for_value_events

    snapshot.forEach((child) => {
                        console.log(child.val());
                        trainingSets.push(child.val());
                    });
    

    我需要在孩子身上调用 val 函数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 1970-01-01
      • 2020-01-06
      • 2021-12-16
      • 2012-08-11
      • 2017-12-24
      • 2019-07-01
      相关资源
      最近更新 更多