javascript - Firebase 上的 forEach 方法调用带有未定义键的子快照的回调

标签 javascript firebase firebase-realtime-database

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

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

Notice: those code's are only examples and used during my work, and it officially comes from Firebase's documentation.

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 结构: Screenshot

和输出: Screenshot

最佳答案

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

    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;

      })
)

关于javascript - Firebase 上的 forEach 方法调用带有未定义键的子快照的回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46133108/

相关文章:

javascript - 如何在javascript中将一个对象的数据复制到另一个对象并执行两个对象值的减法?

javascript - 拆分最后两个词并在 javascript 中过滤

javascript - 多个目录上的全局同步模式

android - Firebase 更新后 Gradle 同步失败

ios - “默认 Firebase 应用尚未配置”错误

ios - 从firebase数据库中检索数据到tableView中的类

javascript - parseInt 为 CSS 属性返回 NaN

ios - Firebase 打印 Analytics SSL 错误,但未使用 Analytics

ios - 无法从 Firebase 正确检索数据

android - Firebase ui - 在 android 中为 FirebaseRecyclerView 设置标题 View