使用变量和字符串串联引用Firebase数据库 [英] Referencing firebase database with a variable and string concatenation

查看:58
本文介绍了使用变量和字符串串联引用Firebase数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如您在下面看到的,我正在尝试从数据库中读取数据列表,然后在javascript中循环遍历结果.每当我打开/刷新页面时,该函数就会运行:

As you can see below i'm trying to read a list of data from the database and then loop over the result, in javascript. The function runs whenever i open/refresh the page:

firebase.database().ref("Users/" + uid + "/rooms").on("value", function(snapshot) {

    snapshot.forEach(function(e) {

         var element = e.val();

         var roomId = element.Id;

    });
});

但是,由于某种原因,用于指定用户ID的字符串串联不起作用.当我直接用用户ID替换它时:

However, that string concatenation to specify the User Id doesn't work for some reason. When i replace it with the user Id directly like this:

firebase.database().ref("Users/GR3JFsMrKOjCrLhDNFMaq72COd07/rooms").on.....

效果很好.但是我当然想使用包含当前用户ID的变量.

that works fine. But of course i want to use the variable which contains the Id of the current user.

在检查用户是否登录时,在onAuthStateChanged中为uid变量分配了一个值:

The uid variable is assigned a value in the onAuthStateChanged when checking if the user is signed in:

firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.

uid = user.uid;

如果我添加如下所示的console.log:

If I add a console.log like this:

firebase.database().ref("Users/" + uid + "/rooms").on("value", function(snapshot) {

console.log(snapshot.parent);

    snapshot.forEach(function(e) {

第一个代码示例(使用uid变量)的输出为:undefined. 如果我直接指定用户ID,则为:room-id-1(我想要的结果).

the output with the first code example (using uid variable) is: undefined. If i specify the User Id directly it is: room-id-1 (the result i want).

如何使字符串串联工作?还是这是指定当前用户路径的错误方法?

How do i make the string concatenation work? Or is this the wrong way of specifying the path of the current user?

推荐答案

问题不太可能出在字符串串联本身上.当您开始从数据库中读取数据时,uid simple可能还没有值的可能性更大.

It is extremely unlikely that the problem is in the string concatenation itself. It is much more likely that uid simple doesn't have a value yet when you start reading from the database.

要确保uid可用,请将数据的读取内容放入身份验证状态侦听器中,如下所示:

To make sure the uid is available, put the reading of the data into the auth state listener like this:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    uid = user.uid;
    console.log("uid="+uid);
    firebase.database().ref("Users/" + uid + "/rooms").on("value", function(snapshot) {
      snapshot.forEach(function(e) {
        var element = e.val();
        var roomId = element.Id;
        console.log("roodId="+roomId);
      });
    });
  }
})

这篇关于使用变量和字符串串联引用Firebase数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆