我有一个配置,我希望能够注入(inject)到 Angular 服务、指令等中。这样做的最佳方法是什么?
我正在玩制作配置模块的想法:
'use strict';
angular.module('config', [])
但我不确定如何构造将成为注入(inject)的实际配置对象的对象文字:
angular.module('myModule', ['ngResource', 'config'])
.factory('myservice', function ($resource) {
return $resource(config.myservice,{}, {
// whatever
})
});
将配置公开为服务并注入(inject)它可以吗?
最佳答案
我想说,策略会有所不同,具体取决于您拥有的配置类型,但您有多种选择:
模块范围的常量
如果只需要几个常量,可以使用.value()
, 像这样:
var app;
app = angular.module("my.angular.module", []);
app.value("baseUrl", "http://myrestservice.com/api/v1");
//injecting the value
app.controller("MyCtrl", ['baseUrl', function (baseUrl) {
console.log(baseUrl); // => "http://myrestservice.com/api/v1"
}]);
查看更详细的答案 here .
获取配置/配置服务
我个人喜欢做的是像往常一样通过服务从其他地方获取我的配置。没关系,这是一个远程位置还是只是静态信息。
var app;
app = angular.module("my.angular.config", []);
app.service('Configuration', [function() {
return {
getbaseUrl: function() { return "http://myrestservice.com/api/v1" },
getConfig: function() {
return {
answer: 42,
question: "??"
}
}
}
}]):
编辑:带有外部提取的示例:
var app;
app = angular.module('my.module.config', []);
app.factory('ConfigurationData', ['$http', '$q', function(http, q) {
var deferredConfig = q.defer();
//error handling ommited
http.get('http://remote.local/config.json').success(function(data) {
return deferredConfig.resolve(data);
});
return {
getConfig: function() {
return deferredConfig.promise;
}
};
}]);
使用此服务,您可以将配置注入(inject)其他服务,但是,您可能会遇到时间问题,因为您必须先注入(inject)并解决服务提供的 promise ,然后才能对配置进行任何操作:
var app;
app = angular.module("my.other.module", ['my.module.config']);
app.factory('MyAwesomeService', ['ConfigurationData', function(config) {
config.getConfig().then(function(config) {
//do something with your config.
});
}]);
您可以在这里获得更精细的控制,因为您可以对不同的输入使用react。同样,这取决于您的用例。如果您需要额外的逻辑来构建配置,您可以在此处使用工厂。
最后,如果您想要更多地控制配置,您可以创建一个
自定义提供程序
提供者可能非常有用,但我认为它们设计起来有点困难。考虑到
baseUrl
根据您的应用程序运行所需的配置,您可以为需要 baseUrl
值的服务编写提供程序。像这样:var app;
app = angular.module('my.angular.module', []);
app.provider("RestServiceProvider", function(){
this.baseUrl = 'http://restservice.com';
this.$get = function() {
var baseUrl = this.baseUrl;
return {
getBaseUrl: function() { return this.baseUrl; }
}
};
this.setBaseUrl = function(url) {
this.baseUrl = url;
};
});
这使您可以在应用程序的配置阶段做一些很酷的事情:
app.config(['RestserviceProvider', function(restServiceProvider) {
restServiceProvider.setBaseUrl('http://wwww.myotherrestservice.com');
}]);
您在服务/ Controller /等中获取的每个实例。的
RestService
现在将有 baseUrl
从您注入(inject)它的那一刻起从配置阶段设置。如需更详细的概述,我建议使用 gist .
关于angularjs - 在 AngularJS 中注入(inject)配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18036629/