我对angular.js很新。这是我写的第一个服务。它需要一个json对象并更新控制器的范围。虽然我对此感到困惑但是...我认为我应该将sseListener的内部代码包装起来并将其作为一个函数返回,但我不确定我是如何编写它的,以及为什么我需要返回它作为一个功能。
另外,如果我将此服务注入多个控制器,那么会增加事件监听器吗?我只想拥有一个事件监听器。
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
});
}
});
答案 0 :(得分:1)
不是直接调用cpuUpdate(我不清楚你的工厂如何获取对这个函数的引用),最好使用$ rootScope。$ broadcast(eventName,data),并对控制器中的事件。此外,您应该从工厂返回一个对象,但由于您不需要在任何地方注入该对象,因此最好将其放入app.run中。以下是我认为您的代码应该与我提到的更改的对应关系:
angular.module('monitorApp').
run(function ($rootScope) { //Inject the $rootScope
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":
// Broadcast the event with data
$rootScope.$broadcast('$cpuResult', result);
break;
}
});
}).
controller('cpuCtrl', function($scope)){
$scope.apiTimeStamp = "";
$scope.infoReceived = "";
$scope.last15 = "";
$scope.last5 = "";
$scope.lastMinute = "";
// Need to pass the event to cpuUpdate,
var cpuUpdate = function (e, 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
});
};
//Listen for the event, call cpuUpdate when caught
$scope.$on('$cpuResult', cpuUpdate);
});