配置依赖于另一个服务angularjs的服务
Configuring a service that depends on another service angularjs
我需要知道的是,如何在$get函数之外使用像$http这样的服务,或者这可能吗?我的代码加载了一个json文件,该文件提供了一个字典,我的应用程序可以通过各种方式使用它。我希望用户能够自定义这个字典,所以我使用jquery的扩展方法来允许用户向对象添加值并扩展字典。下面代码中的instance方法处理所有这些。我想做的是像一样配置我的服务
config(['_sys_dictionaryProvider', function(_sys_dictionaryProvider) {
_sys_dictionaryProvider.instansiate('config/dictionary/custom/dictionary.json');
}])
但这需要$http
服务在配置时可用,我不认为是这样。如果我将$http
服务作为$get属性的一部分,它会起作用,正如这里所解释的,只是每次使用该服务时都必须查询网络。有什么方法可以在配置另一个服务时使用一个服务吗?
下面的完整代码,如果需要澄清,请告诉我。
app.provider("_sys_dictionary", ['$http',
function ($http) {
var dictionary,
DictionaryService = function () {
this.definitions = dictionary;
this.define = function (what) {
var definitions = this.definitions;
if (what instanceof Array) {
for (var i = 0; i < what.length; i++) {
definitions = definitions[what[i]];
}
return definitions;
}
return this.definitions[what];
};
};
return {
$get: function () {
return new DictionaryService();
},
instansiate: function (path) {
$http.get('config/dictionary/dictionary.json').success(function (data) {
dictionary = data;
$http.get(path).success(function (data) {
jQuery.extend(true, dictionary, data)
});
});
}
};
}
]);
我认为在配置阶段不可能使用服务,因为无法保证您使用的服务本身已经配置好,所以我选择了这条路线,而不是
app.provider("_sys_dictionary", function () {
var dictionary,
DictionaryService = function () {
this.definitions = dictionary;
this.define = function (what) {
var definitions = this.definitions;
if (what instanceof Array) {
for (var i = 0; i < what.length; i++) {
definitions = definitions[what[i]];
}
return definitions;
}
return this.definitions[what];
};
};
return {
$get: [
function () {
console.log(dictionary);
return new DictionaryService();
}
],
instansiate: function (path) {
jQuery.ajax({
url: 'config/dictionary/dictionary.json',
success: function (data) {
dictionary = data;
jQuery.ajax({
url: path,
success: function (data) {
jQuery.extend(true, dictionary, data);
},
async: false
});
},
async: false
});
}
};
});
我最终使用了jquery的ajax对象,并将async改为false,因为我需要在使用服务之前准备好字典。希望这能帮助到别人。如果有人知道更好的方法,我很想知道。
相关文章:
- AngularJS-需要在index.html页面中访问来自服务的数据
- 在AngularJS服务中使用$http回调
- 使用服务(AngularJS)在控制器之间共享数据
- 从AngularJS中的另一个文件中的控制器访问服务
- AngularJS 1.5.x服务未正确绑定,并且未在控制器中更新
- AngularJS:使用维基百科API的web服务
- 如何在angularjs上提供服务
- AngularJS中介服务中的解约
- 使用角度模态服务(AngularJS)自定义模态
- 从服务 AngularJS + TypeScript 调用指令
- 无法使用服务AngularJS - “无法读取未定义的属性'原型'”
- 将 localStorage 值传递到服务 angularjs 中
- $broadcast不是从服务(AngularJS)触发的
- 在服务angularjs中的函数中使用$scope
- 配置依赖于另一个服务angularjs的服务
- 在服务AngularJS中存储变量
- forEach内部提供商服务AngularJS
- 从控制器传递多个参数到服务angularjs
- 无法从工厂向服务angularJS返回值
- 只保存服务器上更改的对象:Restful服务+angularjs