在网上收听child_changed(Firebase实时数据库)

时间:2016-06-16 06:23:14

标签: javascript firebase-realtime-database

我是javascript和firebase的新手,我创建了单个网页,因为我想听 child_changed 事件 下面是我的代码

<!DOCTYPE html>
<html>
<body>

<script src="https://www.gstatic.com/firebasejs/3.0.2/firebase.js"></script>
<script>

var config = {
  apiKey: "AIzaSyAqPnuP-EwU2WXreJ_3Ks_er0KbTKE-BNg",
  authDomain: "hellofirebase-a1794.firebaseapp.com",
  databaseURL: "https://hellofirebase-a1794.firebaseio.com"
};

firebase.initializeApp(config);

var commentsRef = firebase.database().ref().child('hellofirebase-a1794');

commentsRef.on('child_changed', function(data) {
window.alert("sometext"+data.val());
});       
</script>   
</body>
 </html>

我的数据库结构如下所示

hellofirebase-a1794
               |
               |
               ------betteryLevel : 12

但是当我从Firebase控制台更改值时,我没有收到事件,也没有在Chrome控制台中出现任何错误,有人请帮我解决问题

2 个答案:

答案 0 :(得分:1)

更改您的代码
var commentsRef = firebase.database().ref().child('hellofirebase-a1794');

为:

var commentsRef = firebase.database().ref().child('/');

您不需要将hellofirebase-a1794(您的根)添加到数据库引用中。

答案 1 :(得分:0)

看起来hellofirebase-a1794是您的项目名称或是根,因此您无需在.ref()之后给孩子。

您可以将数据库引用作为:

var commentsRef = firebase.database().ref();

然后,您可以从commentsRef获取数据。