在我的应用中,我有一个事件可以侦听发送给用户的新消息。收到事件后,它会运行工厂函数来检索消息。但是,似乎总是有1个事件落后(即事件1数据在事件2发生之前不会显示)。
我觉得这与摘要周期有关。我试过$ scope。$ apply,$ timeout无济于事。希望我已经足够清楚了。
$scope.retrieveMessages = function(){
Conversations.retrieveConversations($scope.authentication.uid)
.then(function(success){
$scope.messageList = success;
}, function(error){
console.log(error);
});
};
$scope.$on('$RECEIVED_MESSAGE', function (event, data) {
$scope.retrieveMessages();
$scope.$apply();
});
服务
angular
.module('conversations')
.factory('EventEmitter', ['$rootScope',
function($rootScope) {
var factory = {
newMessage: function() {
$rootScope.$broadcast('$RECEIVED_MESSAGE');
}
};
return factory;
}]);
监视firebase以进行更改的控制器中的功能
var notificationsRef = new Firebase(config.firebaseRef + 'notifications/' + $scope.authentication.uid);
notificationsRef.limitToLast(1).on('child_added', function(childSnapshot, prevChildKey) {
var snapshot = childSnapshot.val();
if(snapshot.type === 'Conversation'){
EventEmitter.newMessage();
};
})
.catch(function(error) {
console.error("Error:", error);
});
对话工厂(省略定义和其他简洁方法)
retrieveConversations: function(uid){
var deferred = $q.defer();
var request = {
uid: uid
};
$http.post(config.serverRef + '/conversations', request)
.success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
deferred.resolve(data);
})
.error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
deferred.reject(status);
});
return deferred.promise;
},
答案 0 :(得分:0)
问题不是代码,而是时间和执行。调用发生的速度比将firebase数据重新索引到elasticsearch更快。解决了$ timeout(function(){$ scope.retrieveMessages()},1000)。