H.L.Alumnus H.L.Alumnus - 5 months ago 22
AngularJS Question

Retrieve data from the new Firebase

I'm using the new Firebase at firebase.google.com for my website.

My database structure:

root

___ [auto-generated ID]

______ key1 : value

______ key2 : value



I followed the method in their document to get value of key1 as below:


database.ref('root/').on('value', function(snapshot) {
var obj = snapshot.val();
alert(obj[0].key1);
});


But I always get the error says that obj[0] is undefined and I can't read its properties. What did I do wrong and how to properly retrieve data from firebase?

Note: I'm using Angularjs for my website

Answer

Got it! alert(obj[0].key1); gives you the error!

instead, try using the below code:

database.ref('root/').on('value', function(snapshot) {
    var obj = snapshot.val();
    obj.forEach(function(data){
        alert(data.key());
    }
});

Also the usage of /root is not advised. Instead, use the url of the data.

The normal format of this url is: <uniqueAppName>.firebaseio.com

var url = "dazzling-inferno-2613.firebaseio.com";
database.ref(url).on('value', function(snapshot) {
    //concepts
});
Comments