【问题标题】:forEach method on Firebase invokes callback with child snapshot with undefined keyFirebase 上的 forEach 方法使用未定义键的子快照调用回调
【发布时间】:2017-09-24 02:41:59
【问题描述】:

我开始学习 JavaScript 已经几个月了,因为我是一名 IOS 开发人员,我也更喜欢 Firebase 作为我网站的后端。

所以在今天的实践中,我曾经读取Firebase数据并提醒自己,我使用了这段代码,

注意:这些代码只是示例,在我的工作中使用,它正式来自 Firebase 的文档。

var query = firebase.database().ref("users").orderByKey();

query.once("value")
  .then(function(snapshot) {
    snapshot.forEach(function(childSnapshot) {
      // key will be "ada" the first time and "alan" the second time
      var key = childSnapshot.key;
      // childData will be the actual contents of the child
      var childData = childSnapshot.val();

        alert(key); // also tried the (key.value); as well
  });

这是我的 Firebase 结构:

和输出:

【问题讨论】:

    标签: javascript firebase firebase-realtime-database


    【解决方案1】:

    这很有趣,但 firebase 不会像 API 更改那样频繁地更新他们的文档,如果您使用的是 Angular 4+,那就更糟了。尝试像下面这样重写您的代码。您需要在使用 forEach 迭代快照后返回一个布尔值:

        var query = firebase.database().ref("users").orderByKey();
        query.once("value", (function(snapshot) {
            snapshot.forEach(function(childSnapshot) {
              // key will be "ada" the first time and "alan" the second time
              var key = childSnapshot.key;
              // childData will be the actual contents of the child
              var childData = childSnapshot.val();
    
              alert(key); // also tried the (key.value); as well
              return true;
    
          })
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-03
      • 1970-01-01
      • 2020-02-09
      • 2019-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-05
      相关资源
      最近更新 更多