I have a webserver that sends SSE events to all clients which works great.
The broadcast to all clients runs once every 2 minutes. If a client
connects between that time, they have to wait until the next broadcast and
their elements show empty data while waiting. To fix this on the webserver
time, when a client connects they will get a single broadcast to them right
away.
The problem is on the client/Angular side. When that first...single-only to
the client that first signed on...gets a broadcast...the
controller's $scope.$watchCollection() misses that first broadcast because
the controller is not fully initialized yet. However, the
service source.addEventListener() does catch the first broadcast
successfully. It's that the controller isn't ready yet and misses it. I
have tried $timeout but that misses up the data because service is used by
other controllers and that data timedelay makes messes up the data
that sseHandler contains.
How can I make it to where the $watchCollection() is ready in time to catch
the first broadcast?
Also, would it be possible to return $scope.$watchCollection() from the
service? Does the service have access to that local scope before it is
injected?
angular.module('monitorApp')
.factory('sseHandler', function ($rootScope) {
var source = new EventSource('/subscribe');
var sseHandler = {};
source.addEventListener('message', function(e) {
$rootScope.$apply(function (){
result = JSON.parse(e.data);
event = Object.keys(result)[0];
switch(event) {
case "cpuResult":
sseHandler.result = result;
console.log(sseHandler.result.cpuResult.timestamp);
break;
}
});
});
return sseHandler;
});
angular.module('monitorApp')
.controller('cpuCtrl', ['$scope', 'sseHandler', function($scope,
sseHandler) {
var cpuUpdate = function (result) {
$scope.available = result.cpuResult.avaiable;
$scope.apiTimeStamp = result.cpuResult.timestamp;
$scope.infoReceived = new Date();
$scope.last15 = result.cpuResult.metrics['15m'].data
$scope.last5 = result.cpuResult.metrics['5m'].data
$scope.lastMinute = result.cpuResult.metrics['1m'].data
}
$scope.$watchCollection(function(){
return sseHandler.result;
}, function(){
if (sseHandler.result.cpuResult) {
console.log("yes");
cpuUpdate(sseHandler.result);
}
});
}]);
--
You received this message because you are subscribed to the Google Groups
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.