我需要在我的AngularJS应用程序启动时加载一个配置文件(JSON格式),以便加载一些将在所有api调用中使用的参数。所以我想知道是否可以在AngularJS中这样做,如果可以,我应该在哪里/何时加载配置文件?
注意:-我需要将配置文件参数保存在服务中,因此我需要在加载任何控制器之前加载json文件内容,但使用可用的服务单元-在我的情况下,使用外部json文件是必须的,因为应用程序客户端需要能够从外部文件轻松更新应用程序配置,而无需查看应用程序源代码。
发布于 2014-04-03 01:07:18
编辑的
听起来您想要做的是使用参数配置服务。为了异步加载外部配置文件,您必须在数据加载完成回调中自己引导angular应用程序,而不是使用自动引导。
考虑以下服务定义的示例,该服务定义实际上没有定义服务URL (类似于contact-service.js
):
angular.module('myApp').provider('contactsService', function () {
var options = {
svcUrl: null,
apiKey: null,
};
this.config = function (opt) {
angular.extend(options, opt);
};
this.$get = ['$http', function ($http) {
if(!options.svcUrl || !options.apiKey) {
throw new Error('Service URL and API Key must be configured.');
}
function onContactsLoadComplete(data) {
svc.contacts = data.contacts;
svc.isAdmin = data.isAdmin || false;
}
var svc = {
isAdmin: false,
contacts: null,
loadData: function () {
return $http.get(options.svcUrl).success(onContactsLoadComplete);
}
};
return svc;
}];
});
然后,在document ready上,调用加载配置文件(在本例中,使用jQuery)。在回调中,您将使用加载的json数据执行您的angular应用程序.config。在运行.config之后,您需要手动引导应用程序。非常重要:如果您正在使用此方法,请不要使用ng-app指令,否则angular将自行引导。有关更多详细信息,请参阅以下url:
http://docs.angularjs.org/guide/bootstrap
如下所示:
angular.element(document).ready(function () {
$.get('/js/config/myconfig.json', function (data) {
angular.module('myApp').config(['contactsServiceProvider', function (contactsServiceProvider) {
contactsServiceProvider.config({
svcUrl: data.svcUrl,
apiKey: data.apiKey
});
}]);
angular.bootstrap(document, ['myApp']);
});
});
更新:这是一个JSFiddle示例:http://jsfiddle.net/e8tEX/
发布于 2014-12-31 05:56:17
我无法让我的基思·莫里斯建议的方法起作用。
因此,我创建了一个config.js文件,并将其包含在index.html中的所有angular文件之前
config.js
var configData = {
url:"http://api.mydomain-staging.com",
foo:"bar"
}
index.html
...
<script type="text/javascript" src="config.js"></script>
<!-- compiled JavaScript --><% scripts.forEach( function ( file ) { %>
<script type="text/javascript" src="<%= file %>"></script><% }); %>
然后在我的运行函数中,我将配置变量设置为$rootScope
.run( function run($rootScope) {
$rootScope.url = configData.url;
$rootScope.foo = configData.foo;
...
})
发布于 2014-04-03 01:14:41
您可以对以下内容使用常量:
angular.module('myApp', [])
// constants work
//.constant('API_BASE', 'http://localhost:3000/')
.constant('API_BASE', 'http://myapp.production.com/')
//or you can use services
.service('urls',function(productName){ this.apiUrl = API_BASE;})
//Controller calling
.controller('MainController',function($scope,urls, API_BASE) {
$scope.api_base = urls.apiUrl; // or API_BASE
});
//在html页面中称为{{api_base}}
还有其他几种选择,包括.value
和.config
,但它们都有自己的局限性。如果您需要联系服务提供商进行一些初始配置,那么.config
是很好的选择。除了可以使用不同类型的值之外,.value
与constant类似。
https://stackoverflow.com/questions/22825706
复制相似问题