我在考虑使用一个服务来存储变量并调用另一个存储调用web1的函数的服务,这些函数将被service1调用 - 这是个坏主意吗?
例如,我有一个只从Service1获取值的控制器:
(function() {
'use strict';
angular
.module('app.event')
.controller('Controller1', Controller1);
Controller1.$inject = ['service1', '$stateParams'];
/**
* Controller 1
* @constructor
*/
function Controller1(service1, $stateParams) {
// Declare self and variables
var vm = this;
vm.number = 0;
init();
/**
* Initializes the controller
*/
function init() {
service1.refreshCount($stateParams.id);
vm.number = service1.getCount();
}
}
})();
下面是Service 1,它只存储变量和对Service2中函数的引用:
(function() {
'use strict';
angular
.module('app.event')
.factory('service1', service1);
service1.$inject = ['service2'];
/**
* The event index service
* @constructor
*/
function service1(service2) {
// Declare
var count = 0;
// Create the service object with functions in it
var service = {
getCount: getCount,
setCount: setCount,
refreshCount: refreshCount
};
return service;
///////////////
// Functions //
///////////////
/**
* Refreshes the count value
*/
function refreshCount(id) {
service2.getCounts(id).then(
function (response) {
setCount(response.data.Count);
});
}
/**
* Returns the count value
*/
function getCount() {
return count;
}
/**
* Updates the count
* @param {int} newCount - The new count value
*/
function setCount(newCount) {
count = newCount;
}
}
})();
以下将是Service2的一部分,其中函数从Service1调用:
// Gets a count from the DB
getCounts: function(id) {
$http({ url: APP_URLS.api + 'WebApiMethodName/' + id, method: 'GET' }).then(function (response) {
return response.data.Count;
});
},
etc : function() {},
etc : function() {}
这是一个好主意,还是以这种方式在服务之间进行沟通有什么不好?