我的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变量中打印出我想要的正确对象。
这是我找到"查询"的参考资料。 https://www.firebase.com/blog/2013-04-12-denormalizing-is-normal.html
答案 0 :(得分:1)
您必须注意 child_added 和值事件是 async 。如果你在控制器的底部放置一个console.log,你可能会看到一个空的对象/数组,因为它们在执行时间内还没有被填充..
请勿忘记调用$ scope。$在异步请求中应用,让您的视图了解变量中的新值。
(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;