I am completely new to working with angular.js. Recently, I wrote my first Service which takes a JSON object and updates the scope of the controller. However, I find myself a bit confused about some aspects of it. Specifically, I am unsure if I should wrap the inner code of sseListener and return it as a function, and why this is necessary.
Furthermore, I am concerned that if I inject this service into multiple controllers, it might result in duplicate event listeners. Ideally, I only want to have one event listener active at all times.
one@demo ~/cloudimageshare-monitoring/project/app/scripts $ cat services/sse_listen.js
angular.module('monitorApp')
.factory('sseListener', function () {
var source = new EventSource('/subscribe');
source.addEventListener('message', function(e) {
var result = JSON.parse(e.data);
event = Object.keys(result)[0];
switch(event) {
case "cpuResult":
cpuUpdate(result);
break;
}
});
}
one@demo ~/cloudimageshare-monitoring/project/app/scripts $ cat controllers/main.js
'use strict';
angular.module('monitorApp')
.controller('homeCtrl', function($scope, $location, $document) {
console.log("s");
});
angular.module('monitorApp')
.controller('cpuCtrl', function($scope) {
$scope.apiTimeStamp = "";
$scope.infoReceived = "";
$scope.last15 = "";
$scope.last5 = "";
$scope.lastMinute = "";
var cpuUpdate = function (result) {
$scope.$apply(function () {
$scope.apiTimeStamp = result.cpuResult.timestamp;
$scope.infoReceived = new Date();
$scope.last15 = result.cpuResult.metrics['1m'].data
$scope.last5 = result.cpuResult.metrics['5m'].data
$scope.lastMinute = result.cpuResult.metrics['15'].data
});
}
});