Firebase set data from database as variable

时间:2018-06-18 11:39:54

标签: javascript html firebase firebase-realtime-database

I've just started using Firebase and i can't get data from database. Here's my code

const books = firebase.database().ref('Books');
var index;
books.once("value", function(snapshot) {
   index = snapshot.val().Count
});

console.log(index)

Console log gives undefined. Where's the problem? Thanks.

3 个答案:

答案 0 :(得分:0)

你遇到的问题是book.once是异步的,所以代码中实际发生的是这个。

//set reference to books
//set variable index to undefined
//start a call to update index
//log the value of index
//call to update value finishes, index gets set to something

尝试在books.once块中移动console.log,并查看该值是否已记录。

答案 1 :(得分:0)

即使console.log尚未完成,您的通话也是异步的.once()已执行。

这样做:

books.once("value", function(snapshot) {
  index = snapshot.key; // Count doesn't exist, the index is called "key" in firebase
  return snapshot.val();
}).then(function(books) {
  // This basically makes sure that the .once() callback has been done. Now you can see what's in `books`.
  console.log(books);
});

编辑:您无法在异步操作之外访问.val() booksTake a look here for more about async operations

答案 2 :(得分:0)

  

这样做:

const books = firebase.database().ref('Books');
var index;
books.once("value", function(snapshot) {
  index = snapshot.val().Count
}).then(function() {
  console.log(index)
});

发生的事情是数据是临时的,如果你试图从Firebase函数外部读取'index','index'将为空,它将返回null,导致'undefined',所以你需要把' console.log'在'then(func())函数中运行,或者在'once(action,func())'函数中使用变量set函数。