有没有办法在Firebase中制作实时ForEach?

Lui*_*uez 0 javascript foreach firebase firebase-realtime-database

我一直在使用ForEach来填充我的HTML表格.

到目前为止这么好但桌子不是实时的.我必须重新加载它的功能才能再次获取结果.如果我添加或删除条目,则在重新加载之前不会发生任何错误.

有没有办法让这个实时?来自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();
});
});
Run Code Online (Sandbox Code Playgroud)

请原谅我对JS的不了解,我正在研究它.

Fra*_*len 7

通过使用once()您告诉数据库您只想获得当前值而不关心更新.

获得实时更新的解决方案就是使用on().由于promise只能在on()为每次更新调用处理程序时解析一次,因此您应该使用回调on():

var query = firebase.database().ref("users").orderByKey();
query.on("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();
  });
}, function(error) {
  console.error(error);
});
Run Code Online (Sandbox Code Playgroud)

如果您关心更新UI以响应此类更新,您可能希望使用child_处理程序.这些在JSON树中被称为低一级,因此在您的情况下,对于添加/更改/删除的每个用户.这允许您更直接地更新UI.例如,上述child_added事件可能是:

var query = firebase.database().ref("users").orderByKey();
query.on("child_added", function(snapshot) {
    var key = snapshot.key;
    var data = snapshot.val();
    // TODO: add an element to the UI with the value and id=key
  });
}, function(error) {
  console.error(error);
});
Run Code Online (Sandbox Code Playgroud)

现在您可以使用以下方式处理其他事件:

query.on("child_changed", function(snapshot) {
  // TODO: update the element with id=key in the update to match snapshot.val();
})
query.on("child_removed", function(snapshot) {
  // TODO: remove the element with id=key from the UI
})
Run Code Online (Sandbox Code Playgroud)

我们的Web开发人员指南参考文档中详细介绍了这一点以及更多内容.