问题描述
我对 angularjs
还很陌生,找不到任何文档或示例为了这.我想要做的是扩展基本服务,以便我可以使用其他服务在基本服务下定义的方法.例如,假设我有如下基本服务.
I am fairly new to angularjs
and am not able to find any documentation or examples for this. What I am looking to do is to extend a basic service so that i can use the methods defined under the basic service from other services. So for example say i have a basic service as follows.
angular.module('myServices', []).
factory('BasicService', function($http){
var some_arg = 'abcd'
var BasicService = {
method_one: function(arg=some_arg){ /*code for method one*/},
method_two: function(arg=some_arg){ /*code for method two*/},
method_three: function(arg=some_arg){ /*code for method three*/},
});
return BasicService;
}
);
现在我想定义一个扩展服务,它从上面的BasicService
扩展而来,这样我就可以从我的扩展服务中使用在 BasicService 下定义的方法.也许是这样的:
Now i want to define an Extended service that extends from the above BasicService
so that i can use methods defined under the BasicService from my extended service. Maybe something like:
factory('ExtendedService', function($http){
var ExtendedService = BasicService();
ExtendedService['method_four'] = function(){/* code for method four */}
return ExtendedService;
}
推荐答案
你的 ExtendedService
应该注入 BasicService
以便能够访问它.除此之外,BasicService
是一个对象字面量,因此您实际上不能将其称为函数 (BasicService()
).
Your ExtendedService
should inject the BasicService
in order to be able to access it. Beside that BasicService
is an object literal, so you can't actually call it as function (BasicService()
).
.factory('ExtendedService', function($http, BasicService){
BasicService['method_four'] = function(){};
return BasicService;
}
这篇关于我如何扩展服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!