Firebase无法从数据库中获取价值

时间:2016-12-06 14:57:58

标签: angularjs firebase ionic-framework firebase-realtime-database

我尝试使用Firebase和Ionic构建聊天应用程序。

如果我直接通过以下网址打开聊天页面:

http://localhost:8100/#/home/messaging/jJ53KWgqnuWXSzksRYl1XNw20JJ2

Firebase似乎无法正常运行。但是,如果我打开上一页菜单中的聊天页面:

ui-sref="home.messaging({id: p.friendId})"

一切正常。

这是我在ChatController上的代码:

$scope.data.friendId = $stateParams.id;

var refMessage = firebase.database().ref();

refMessage.child("user_profile").child($scope.data.friendId).once("value")
        .then(function (profile) {
            $scope.data.friendUserProfile = profile.val();
            //on debug this line is reached
        });

refMessage.child("profile_photo").child($scope.data.friendId).once("value")
        .then(function (profilePic) {
            $scope.data.friendUserPhotos = profilePic.val();
            //I can't get friend's photos firebase doesnt reach this line.

        });

refMessage.child("friends").child($localStorage.uid).child($scope.data.friendId).once("value")
        .then(function (friend) {
            if (friend.val() !== null) {
                $scope.data.isNewFriend = friend.val().isNew;
                //on debug this line is reached
            }
        });

var chatId = 'chat_' + ($scope.data.uid < $scope.data.friendId ? $scope.data.uid + '_' + $scope.data.friendId : $scope.data.friendId + '_' + $scope.data.uid);

问题只出在朋友的照片上。 Firebase不会从数据库中调用照片。所有其他调用都可以很好地执行异步操作,但在调试时永远无法获得照片。

如果我刷新页面会出现此问题,如果转到上一页并返回聊天页面,则一切正常。

我认为如果$scope.data存在问题。它不适用于之前的friendUserProfile调用,但它适用于它。

Firebase v3.6.1

由于

2 个答案:

答案 0 :(得分:1)

由于firebase是异步的,因此您使用promises来处理异步操作。这意味着您应该添加一个catch方法,以查看Firebase是否返回错误。

如果你不这样做,你将无法确定是否发生错误。

refMessage.child("profile_photo").child($scope.data.friendId).once("value")
    .then(function (profilePic) {
        $scope.data.friendUserPhotos = profilePic.val();
        //I can't get friend's photos firebase doesnt reach this line.

    }).catch(function(error) {
        console.log(error);
    });

答案 1 :(得分:0)

使用firebase.database.enableLogging(true);进行调试后,我已经找到了听众的内容。

在RootController上还有另一个refMessage.child("profile_photo")的调用,如果我直接刷新聊天页面,.once关闭该路径上的所有监听器,我就无法从我的ChatController中获取数据&#39; s firebase电话。

相关问题