AngularJS事件-dom更新延迟
在我的应用程序中,我有一个事件,用于侦听发送给用户的新消息。收到事件后,它运行一个工厂函数来检索消息。然而,似乎它总是落后于1个事件(即,事件1数据直到事件2发生才显示) 我觉得这与消化周期有关。我已尝试$scope.$apply,$timeout,但无效。希望我已经足够清楚了AngularJS事件-dom更新延迟,angularjs,Angularjs,在我的应用程序中,我有一个事件,用于侦听发送给用户的新消息。收到事件后,它运行一个工厂函数来检索消息。然而,似乎它总是落后于1个事件(即,事件1数据直到事件2发生才显示) 我觉得这与消化周期有关。我已尝试$scope.$apply,$timeout,但无效。希望我已经足够清楚了 $scope.retrieveMessages = function(){ Conversations.retrieveConversations($scope.authentication.uid)
$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);
});
对话工厂(为简洁起见,省略了定义和其他方法)
问题不在于代码,而在于时间和执行。调用的速度快于将firebase数据重新索引到elasticsearch。用$timeout(function(){$scope.retrieveMessages()},1000)解决。事件从何处广播?它从使用$rootScope的事件处理/通知服务广播。$broadcast(“$RECEIVED_MESSAGE”);您需要显示是什么触发了
$rootScope.$broadcast
。
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;
},