首页 > 解决方案 > 等到在 Firebase 数据库(网络)中检测到新数据

问题描述

在此示例中,我想在 firebase 数据库的父节点中创建一个名为“friend”的新节点时更改站点。我不知道如何让它等到它检测到新节点。

    var friendUid;
    firebase.database().ref('users/' + uid).child('friend').on('value', function(snapshot){
       friendUid = snapshot.val();
    })
    while(!friendUid){ //I've also tried with "friendUid == null"
     firebase.database().ref('users/' + uid).child('friend').on('value', function(snapshot){
       friendUid = snapshot.val();
     })
    }
    window.document.location = "whatever.html";

标签: javascriptfirebasefirebase-realtime-database

解决方案


您不需要循环,但您确实需要将更改位置的代码移动侦听器中:

firebase.database().ref('users/' + uid).child('friend').on('value', function(snapshot){
  var friendUid = snapshot.val();
  if (friendUid == "what you're looking for") {
    window.document.location = "whatever.html";
  }
})

如果您只想检查节点是否存在,可以简化为:

firebase.database().ref('users/' + uid).child('friend').on('value', function(snapshot){
  if (snapshot.exists()) {
    window.document.location = "whatever.html";
  }
})

推荐阅读