使用 Ionic 在 firebase 中从 children 检索 children

Retrieving children from children in firebase with Ionic

我正在尝试检索 Ionic 中所有用户的帖子(没有特定的用户 ID)。我可以获取数据库中第一个用户的所有帖子,但无法获取其他用户的帖子。

这是我的 firebase 结构的简化版本:

"posts_meta" : {

   "uid" : {

     "post-id" : {
        "title": "",
        "content": ""
     },
   },

   "uid" : {

     "post-id" : {
        "title": "",
        "content": ""
     },
     "post-id" : {
        "title": "",
        "content": ""
     },
   }

在这里,我尝试先遍历用户,然后使用嵌套的 foreach 遍历每个用户的帖子:

.factory('Timeline', function($q, Profile, Utils, Codes) {

var self = this;

self.getAllPosts = function() {
    var qGet = $q.defer();
    var ref = new Firebase(FBURL);

    ref.child("posts_meta").once("value", function(snapshot) {

        snapshot.forEach(function(childSnapshot) {

            childSnapshot.forEach(function(grandchildSnapshot) {
                qGet.resolve(grandchildSnapshot.val());
            })
        })
}, function (error) {
        Codes.handleError(error);
        qGet.reject(error);
    });
    return qGet.promise;
};

我做错了什么?我错过了什么吗?

您不能为一个 promise 调用多个 resolve。承诺在第一个循环迭代中得到解决,然后其他人被忽略。

您可以尝试将所有孙子保存到一个数组中,但我相信 firebase 有办法以更好的性能解决这个问题。

    var values = [];

    snapshot.forEach(function(childSnapshot) {

        childSnapshot.forEach(function(grandchildSnapshot) {
            values.push(grandchildSnapshot);

        })
     })
     promise.resolve(values)