我有一个返回资源的通用服务,需要在另一个服务上附加新方法。这可能吗?
app.factory('FooFactory', function ($resource) {
var model = $resource(
'/:controller/:action/:id',
{ controller: '@controller', id: '@id' },
{ 'foo': { method: 'GET', params: { action: 'foo' } }
});
return model;
});
app.factory('BarFactory', function ($resource, FooFactory) {
var model = FooFactory;
model.bar = ???
return model;
});
答案 0 :(得分:0)
我会这样做:
app.factory('FooFactory', [ '$resource', function($resource) {
var foo = $resource('/:controller/:action/:id',
{ controller: '@controller', id: '@id' },
{ 'foo': { method: 'GET', params: { action: 'foo' } } }
);
var getFoo = function() {
return foo;
};
return {
getFoo: getFoo
};
}]);
app.factory('BarFactory', [ 'FooFactory', function(FooFactory) {
var foo = FooFactory.getFoo();
// not totally clear what your goal is here
// if bar is just part of foo
// foo.bar = {};
// if bar is like foo but then you want to modify things
var bar = $.extend(true, {}, foo); // with jQuery
// var bar = _.cloneDeep(foo); // lodash way
var getBar = function() {
return bar; // or foo.bar if it is just a part of foo
};
return {
getBar: getBar
};
}]);
如果目标是修改FooFactory返回的foo,那么FooFactory中的setter类型函数可能会更好,这样BarFactory就可以进行计算并调用FooFactory.setBar(无论如何);