AngularJS load config on app start

后端 未结 5 1891
南方客
南方客 2020-12-12 21:38

I need to load a config file (JSON format) upon my AngularJS app startup in order to load few parameters which will be used in all api calls. So I was wondering if it is pos

5条回答
  •  温柔的废话
    2020-12-12 22:43

    EDITED

    It sounds like what you are trying to do is configure a service with parameters. In order to load the external config file asynchronously, you will have to bootstrap the angular application yourself inside of a data load complete callback instead of using the automatic boostrapping.

    Consider this example for a service definition that does not actually have the service URL defined (this would be something like 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;
        }];
    });
    

    Then, on document ready, you would make a call to load your config file (in this case, using jQuery). In the callback, you would then do your angular app .config using the loaded json data. After running the .config, you would then manually bootstrap the application. Very Important: do not use the ng-app directive if you are using this method or angular will bootstrap itself See this url for more details:

    http://docs.angularjs.org/guide/bootstrap

    Like so:

    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']);
        });
    });
    

    UPDATE: Here is a JSFiddle example: http://jsfiddle.net/e8tEX/

提交回复
热议问题