我需要在 AngularJS 应用程序启动时加载一个配置文件(JSON 格式),以便加载一些将在所有 api 调用中使用的参数。所以我想知道是否可以在 AngularJS 中这样做,如果可以的话我应该在哪里/何时加载配置文件?
注意: - 我需要将配置文件参数保存在服务中,因此我需要在加载任何 Controller 之前加载 json 文件内容,但有可用的服务单元 - 在我的例子中,必须使用外部 json 文件,因为应用程序客户端需要能够从外部文件轻松更新应用程序配置,而无需遍历应用程序源。
最佳答案
已编辑
听起来您正在尝试做的是使用参数配置服务。为了异步加载外部配置文件,您必须在数据加载完成回调中自行引导 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;
}];
});
然后,在文档准备好后,您可以调用来加载您的配置文件(在本例中,使用 jQuery)。在回调中,您将使用加载的 json 数据执行 Angular app .config。运行 .config 后,您将手动引导应用程序。 非常重要:如果您使用此方法,请不要使用 ng-app 指令,否则 Angular 将自行引导请参阅此网址了解更多详细信息:
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/
关于AngularJS 在应用程序启动时加载配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22825706/