I have the following object:
root: {
id1: { /* this is an autogenerated id by Firebase */
name1: "abc",
name2: "xyz"
},
id2: {
name1: "abc",
name2: "xyz"
},
id3: {
name1: "abc",
name2: "xyz"
},
}
My code to retrieve the whole snapshot is:
getRoot () {
firebase.database ().ref ('roots/')
.on('value', function (snapshot) {
console.log (snapshot.val());
})
}
Everything is perfect. I got every object from the root component, but I can't figure out how to access the IDs and their children? Thanks!
I didn't remember I posted this question. I found out how to do this long time ago.
Here is the code that will do the job:
Service:
myFunction () {
var ref = firebase.database ().ref ('roots')
return new Promise ((resolve, reject) => {
ref.on ('value', function (snapshot) {
if (snapshot.val () == null) {
reject (null);
} else {
var list = new Array ();
snapshot.forEach (function (data) {
var item = {
key: data.key, //this is to get the ID, if needed
name1: data.val ().name1,
name2: data.val ().name2,
}
list.push (item);
});
resolve (list);
}
});
});
}
Component:
this.myService.myFunction ().then (objects => {
this.objects = objects;
for (let obj of this.objects) {
console.log (obj.key);
}
}).catch (error => {
alert ('Nothing found');
})
Wish you a happy coding!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With