AngularJS load config on app start

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

    To json config file, there is a practice example on Jaco Pretorius blog's. Basically:

    angular.module('plunker', []);
    angular.module('plunker').provider('configuration', function() {
      let configurationData;
    
      this.initialize = (data) => {
        configurationData = data;
      };
    
      this.$get = () => {
        return configurationData;
      };
    });
    
    angular.module('plunker').controller('MainCtrl', ($scope, configuration) => {
      $scope.externalServiceEnabled = configuration.external_service_enabled;
      $scope.externalServiceApiKey = configuration.external_service_api_key;
    });
    
    angular.element(document).ready(() => {
      $.get('server_configuration.json', (response) => {
        angular.module('plunker').config((configurationProvider) => {
          configurationProvider.initialize(response);
        });
    
        angular.bootstrap(document, ['plunker']);
      });
    });
    

    Plunker: http://plnkr.co/edit/9QB6BqPkxprznIS1OMdd?p=preview

    Ref: https://jacopretorius.net/2016/09/loading-configuration-data-on-startup-with-angular.html, last access on 13/03/2018

提交回复
热议问题