Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve an object ID generated by Firebase?

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!

like image 784
RaulGM Avatar asked Sep 29 '16 16:09

RaulGM


1 Answers

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!

like image 125
RaulGM Avatar answered Oct 18 '22 14:10

RaulGM