I have an AngularJS app with the following controller. It worked fine with GET on regular JSON resource and manual request for updates, but I cannot make it work with Server-Sent Events. The problem I am facing is that after I receive an SSE event and set/update openListingsReport variable my view is not getting updated. I am obviously missing a very basic concept. Please help me fix this.
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)
undefined
ornull
or just blank? Try attaching the message event like this:source.addEventListener('message', function(e) { console.log(e.data); }, false);
I found this article helpful: html5rocks.com/en/tutorials/eventsource/basics – TrazeK$scope
declaration inside the$apply()
:$scope.$apply(function(){ $scope.openListingsReport = event.data;});
Check this out: smartjava.org/content/… – TrazeK$scope.$apply();
Dirty checking should handle the vast majority of cases, including this one – Mawg says reinstate Monica