【问题标题】:Retrieving Firebase Child Value in Javascript在 Javascript 中检索 Firebase 子值
【发布时间】:2020-05-30 09:20:34
【问题描述】:
function sontinue() {
    var user = firebase.auth().currentUser;
    var uid = user.uid; 

    var adaRef = firebase.database().ref("User/" + uid);
    if (adaRef.orderByChild("Role").equalTo("admin")) {
        location.href = "DB.html";
    } else {
        location.href = "index.html";
    }

}

我想将我的 "admin" 帐户链接到 DB.html 并将 "user" 帐户链接到 index.html 但我认为我在检索子值时总是失败。

【问题讨论】:

  • 好像firebase.auth().currentUser返回了一个promise,需要异步处理,如果是promise,使用then或者await
  • 是否可以在一个 JavaScript 文件中使用 firebase.auth().currentUser 两次?如果可以的话,我使用两个 firebase.auth().currentUser 而另一个没有承诺。谢谢你的回复顺便说一句...
  • 如果你在这个函数的开头console.log(firebase.auth().currentUser),它会打印什么?
  • 你应该使用on事件监听器来从firebase.database()中读取数据; adaRef.on("value", (snapshot) => // 你的代码在这里)
  • Afrandra,如果您认为我的答案适合您,请单击答案旁边的绿色勾号。有关如何回答某人问题的更多详细信息,请参见此处:stackoverflow.com/help/someone-answers

标签: javascript firebase firebase-realtime-database


【解决方案1】:

您没有从服务器检索数据。请记住,您需要调用 .once('value') 来获取您的查询,然后根据它们的值是管理员还是用户来迭代剩余的代码。 Firebase Docs has more explination我已经修改了你的代码并放在下面

  function sontinue() {
            var user = firebase.auth().currentUser;
            var uid = user.uid; 

            var adaRef = firebase.database().ref("User/" + uid).orderByChild("Role");
            //you now need to retrieve the data

            return adaRef.once('value').then((snapshot)=>{
                return snapshot.forEach(snapshot=>{
                if (snapshot.child("Role").val()==="admin") {
                location.href = "DB.html";
                 } else {
                location.href = "index.html";
                }
                return console.log("added");
                })

            })


        }

如果你只是想找出谁是管理员类型的用户...我会在下面使用它...效率更高。

   function sontinue() {
        var user = firebase.auth().currentUser;
        var uid = user.uid; 

        var adaRef = firebase.database().ref("User/" + uid).orderByChild("Role").equalTo("admin");
        //you now need to retrieve the data

        return adaRef.once('value').then((snapshot)=>{
            //you now have all the users that are just admins
            return snapshot.forEach(snapshot=>{
            location.href = "DB.html";
            return console.log("added");
            })

        })


    }

【讨论】:

  • 如果答案对您有用,请不要忘记投票/单击答案旁边的绿色勾号表示正确:stackoverflow.com/help/someone-answers。
猜你喜欢
  • 1970-01-01
  • 2016-10-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-24
  • 1970-01-01
  • 2018-05-01
  • 1970-01-01
相关资源
最近更新 更多