How to get the object identifier 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 for taking the whole snapshot:

getRoot () {
    firebase.database ().ref ('roots/')
      .on('value', function (snapshot) {
        console.log (snapshot.val());
      })
  }

Everything is perfect. I got each object from the root component, but I can’t figure out how to access the identifiers and their children? Thank!

+4
source share
2 answers

I did not remember that I posted this question. I learned how to do this a long time ago.

Here is the code that will complete the task:

Services:

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');
})

We wish you a happy coding!

+6
source

Change this line of code:

firebase.database ().ref ('roots/')

:

firebase.database ().ref ('roots/id1/name1')

This value will have the value 'name1'.

-1
source

Source: https://habr.com/ru/post/1656252/


All Articles