web – 如何检索Firebase生成的对象ID?

我有以下对象:

root: {
  id1: { /* this is an autogenerated id by Firebase */
    name1: "abc",
    name2: "xyz"
  },
  id2: {
    name1: "abc",
    name2: "xyz"
  },
  id3: {
    name1: "abc",
    name2: "xyz"
  },
}

我检索整个快照的代码是:

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

一切都很完美.我从根组件中获取了所有对象,但我无法弄清楚如何访问ID及其子代?谢谢!

最佳答案
我不记得我发布了这个问题.我很久以前就发现了这个怎么做.

这是完成工作的代码:

服务:

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

零件:

this.myService.myFunction ().then (objects => {
  this.objects = objects;
  for (let obj of this.objects) {
    console.log (obj.key);
  }
}).catch (error => {
  alert ('Nothing found');
})

祝你编码愉快!

转载注明原文:web – 如何检索Firebase生成的对象ID? - 代码日志