AngularJS load config on app start

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

    You can use constants for things like this:

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

    //in html page call it {{api_base}}

    There are also several other options including .value and .config but they all have their limitations. .config is great if you need to reach the provider of a service to do some initial configuration. .value is like constant except you can use different types of values.

    https://stackoverflow.com/a/13015756/580487

提交回复
热议问题