AngularJS load config on app start

后端 未结 5 1897
南方客
南方客 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:40

    Solved by using constant. Like providers you can configure it in .config phase. Everything else like Keith Morris wrote before. So the actual code would be look like this:

    (function () {
    var appConfig = {
    
    };
    
    angular.module('myApp').constant('appConfig', appConfig);
    })();
    

    then in app.bootstrap.js

    (function () {
    
    angular.element(document).ready(function () {
    
        function handleBootstrapError(errMsg, e) {
            console.error("bootstrapping error: " + errMsg, e);
        }
    
        $.getJSON('./config.json', function (dataApp) {
            angular.module('myApp').config(function (appConfig) {
                $.extend(true, appConfig, dataApp);
                console.log(appConfig);
            });
    
            angular.bootstrap(document, ['myApp']);
    
        }).fail(function (e) {
            handleBootstrapError("fail to load config.json", e);
        });
    
    });
    })();
    

提交回复
热议问题