我有一个Angular工厂,我使用揭示模块模式来公开服务接口。工厂使用其他注入的依赖项来支持公共服务本身未包含的公共服务。我理解为什么下面的代码被破坏了,但我要问的是,是否有标准模式可以实现这一目标?我没有太多运气找出正确的模式,以便在调用公共服务时让我访问私有成员/函数。任何指针都表示赞赏。在下面的代码中,如果控制器调用myfactory.initData();
,则无法访问私有函数和变量。
(function () {
'use strict';
angular.module('app').factory('myFactory', ['common', 'config', myFactory]);
function myFactory(common, config) {
var data = { cogs: [], widgets: [] };
var dep = config.dependency;
// Return this factory service definition
var service = {
data: data,
initData: initData,
reset: reset
};
return service;
function initData(forceRefresh) {
_private1(); // out of scope, not part of returned service
_private2(); // out of scope, not part of returned service
}
function _private1() {
// get cogs, from non-exposed private
dep.f1();
}
function _private1() {
// get cogs, from non-exposed private
dep.f2();
}
}
})();
答案 0 :(得分:1)
您无法访问私有函数,因为您在范围内没有对它们的任何引用 - 将它们保存到变量中以使它们保持在范围内:
(function () {
'use strict';
angular.module('app').factory('myFactory', ['common', 'config', myFactory]);
function myFactory(common, config) {
var data = { cogs: [], widgets: [] };
var dep = config.dependency;
var _private1 = function() {
// get cogs, from non-exposed private
dep.f1();
}
var _private1 = function() {
// get cogs, from non-exposed private
dep.f2();
}
// Return this factory service definition
var service = {
data: data,
initData: initData,
reset: reset
};
return service;
function initData(forceRefresh) {
_private1(); // out of scope, not part of returned service
_private2(); // out of scope, not part of returned service
}
}
})();