简体   繁体   中英

How to get Data from Firebase-Database in Real-Time with Javascript

Hello I would like to automatically generate an alert in realtime as soon as a value in my Firebase database has changed. My code looks like this:

try {
        var ref = firebase.database().ref("URL").child("1");
        ref.on("child_changed", function(snapshot) {
          var changedPost = snapshot.val();
          alert(changedPost);
        });
        }
        catch(err) {
          alert("Error");
        }

As you can see the structure of my database is:

这是我的 firebase-database 结构图片的链接。

Could someone tell me what is wrong with this code and why I don't get an alert when something changes in my database?

I would appreciate an answer.

You're listening for child_changed events, which fires when a property under /URL/1 changes. To instead get called when the value in /URL/1 changes, listen for a value event:

ref.on("value", function(snapshot) {
  var changedPost = snapshot.val();
  alert(changedPost);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM