首页 文章

如何使用自己的索引查询特定用户信息并将其传递给$ firebaseArray以便与我的视图同步?

提问于
浏览
0

我的firebase数据库中有以下结构:

{
rooms: {
    LKVmdIPX2_235ksf: {
        members: {
            poasj12O-s657-235a-1236-9832lksf976c: true
        },
        name: Room 1,
        public: true
    },
    KS0sk21gleascm14: {
        members: {
            poasj12O-s657-235a-1236-9832lksf976c: true
        },
        name: Room 2,
        public: true
    }
},
users: {
    poasj12O-s657-235a-1236-9832lksf976c: {
        rooms: {
            LKVmdIPX2_235ksf: true,
            KS0sk21gleascm14: true
        },
        name: Filler
        email: filler@filler.com
    }
}

为了从特定用户获得每个房间(在这种情况下,用户使用= poasj12O-s657-235a-1236-9832lksf976c)我已经完成了以下操作:

$scope.rooms = {};
var ref = new Firebase('URL'); 
var userRef = ref.child('users').child(uid); // I'm manage to get the user's UID after login;
var roomRef = ref.child('rooms');

userRef.child('rooms').on('child_added', function(data) {
    roomRef.child(data.key()).on('value', function(rData) {
       console.log(rData.val()); // prints each room object
       $scope.rooms = $firebaseArray(rData.ref()); 
    });
});

所以为了能够在我尝试的视图中显示该信息:

$scope.rooms = $firebaseArray(rData.ref());

问题是当我做 console.log($scope.rooms) 时我只得到一个空对象,如果我把它放在视图中 {{rooms}} 它甚至会向我显示用户拥有的所有房间 .

那么这是我的问题,如何用我自己的索引查询特定的用户信息并将其传递给$ firebaseArray以便与我的视图同步?

OBS: console.log(rData.val()) 在$ scope.room变量中打印出我想要的正确对象 .

这是我发现"query" https://www.firebase.com/blog/2013-04-12-denormalizing-is-normal.html的参考资料

1 回答

  • 1

    您必须注意 child_addedvalue 事件是 async . 如果你在控制器的底部放置一个console.log,你可能会看到一个空的对象/数组,因为它们在执行时间内还没有填充 .

    不要忘记在异步请求中调用$ scope . $ apply,以便让您的视图了解变量中的新值 .

    (function() {
    app.controller('lobbyController',
        function($rootScope, $scope, $state, $ionicHistory, $firebaseArray, $firebaseObject, firebaseObj, nodes) {
    
      $scope.rooms = []; // initialize an empty array 
    
      $scope.campaigns = {};
        var uid = $rootScope.authData.uid;
      var userInfo;
      userRef     = firebaseObj.child(nodes.USER_NODE).child(uid);
      campaignRef = firebaseObj.child(nodes.CAMPAIGN_NODE);
    
      userRef.child(nodes.CAMPAIGN_NODE).on('child_added', function(data) {
          campaignRef.child(data.key()).on('value', function(cData) {
            // force the view to rerender after a new value came from firebase
            $scope.$apply(function() {
              // push the room to rooms array
              $scope.rooms.push(cData.val());
            })
          });
      });
    
        $scope.createCampaign = function() {
            $state.go('createCampaign');
        }
        }
    );
    })();
    

    调试$ scope的一个好方法是将它暴露给window对象,然后在浏览器控制台上进行检查 . 在你的控制器内放下以下代码:

    window.$scope = $scope;
    

相关问题