AngularJS 在应用程序启动时加载配置

标签 angularjs

我需要在 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/

相关文章:

javascript - 带有 Razor 表达式的 ng-init

javascript - 如何在文件列表的循环中以 Angular 进行同步 http 请求?

javascript - 在 $state.go 之后执行 $window.location.reload(true)

javascript - 无法获得 Angularjs 在 html 页面中显示为表达式的结果

javascript - ngOptions 在自定义指令中应用了两次

AngularJS NodeJS HTTPS 请求

javascript - AngularJS ng-init 在 ng-repeat 中不起作用

angularjs - 错误 : [$compile:nonassign] Expression used with directive 'uibTab' is non-assignable

javascript - 使用 javascript 更改 Accept-Language header

javascript - 如何在没有 jQuery 的情况下使用 $http 发布 urlencoded 表单数据?