我有一个AngularJS应用程序,其中包含以下控制器。它可以正常使用普通的JSON资源进行GET请求和手动请求更新,但是我无法使用服务器推送事件使其工作。我面临的问题是,在我收到SSE事件并设置/更新openListingsReport变量之后,我的视图没有得到更新。我显然缺少一些非常基本的概念,请帮助我解决这个问题。
var rpCtrl = angular.module('rpCtrl', ['rpSvc']);
rpCtrl.controller('rpOpenListingsCtrl', ['$scope', 'rpOpenListingsSvc',
function ($scope, rpOpenListingsSvc) {
$scope.updating = false;
if (typeof(EventSource) !== "undefined") {
// Yes! Server-sent events support!
var source = new EventSource('/listings/events');
source.onmessage = function (event) {
$scope.openListingsReport = event.data;
$scope.$apply();
console.log($scope.openListingsReport);
};
}
} else {
// Sorry! No server-sent events support..
alert('SSE not supported by browser.');
}
$scope.update = function () {
$scope.updateTime = Date.now();
$scope.updating = true;
rpOpenListingsSvc.update();
}
$scope.reset = function () {
$scope.updating = false;
}
}]);
console.log($scope.openListingsReport)
给我正确的更新值!就像我说的,我已经在JS中得到了这个值。我只是不知道为什么AngularJS不会用它来更新网页。 - krl$scope
声明放在$apply()
内部:$scope.$apply(function(){ $scope.openListingsReport = event.data;});
参考这个链接:http://www.smartjava.org/content/html5-server-sent-events-angularjs-nodejs-and-expressjs - TrazeK$scope.$apply();
脏检查应该处理绝大多数情况,包括此情况。 - Mawg says reinstate Monica