Referencing firebase database with a variable and string concatenation

穿精又带淫゛_ 提交于 2020-06-17 00:13:08

问题


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;

    });
});

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.....

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

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;

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) {

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?


回答1:


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.

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);
      });
    });
  }
})


来源:https://stackoverflow.com/questions/50424539/referencing-firebase-database-with-a-variable-and-string-concatenation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!