In order to delay the first iteration of the broadcast until the controller's $watchCollection is ready, I attempted using setTimeout() but it did not work as expected. Even trying with $timeout yielded the same result. What could be causing this issue?
angular.module('monitorApp')
.factory('sseHandler', function ($rootScope) {
var source = new EventSource('/subscribe');
var sseHandler = {};
setTimeout(function() {
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;
}, 1000);
});
EDIT: After investigating further, I discovered that when a client connects to the node server, an SSE broadcast is immediately sent. While the Service source.addEventListener successfully captures this initial broadcast, the controller is not prepared at that moment which causes $scope.$watchCollection to miss the first broadcast.
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);
}
});
}]);