How to set a variable from an $http call then use it in the rest of the application WITHOUT making the whole application asynchronous

后端 未结 4 1802
伪装坚强ぢ
伪装坚强ぢ 2021-01-23 09:05

I have this data

{
  \"config\": {
    \"RESTAPIURL\": \"http://myserver/myrestsite\"
  }
}

and I have this factory that reads that data

4条回答
  •  无人共我
    2021-01-23 09:33

    Adding a bit to what @ThinkingMedia was saying in the comment, with ui-router when defining controllers you can add a resolve parameter.

    In it you can specify some promises that have to resolve before the controller is instantiated, thus you are always sure that the config object is available to the controller or other services that the controller is using.

    You can also have parent/child controllers in ui-router so you could have a RootController that resolves the config object and all other controllers inheriting from RootController

    .state('root', {
        abstract: true,
        template: '',
        controller: 'RootController',
        resolve:{
          config: ['api', function(api){
            return api.initialize();
          }       
        }
      });
    

    and your api factory:

    angular.module('myApp').factory('api',
      ["$http", "$q",
      function ($http, $q) {
        var _configObject = null;
    
        function initialize() {
          return $http.get('/scripts/constants/config.json')
          .then(function (data) {
              _configObject = data;
              return data;
          });
        }
    
        // you can call this in other services to get the config object. No need to initialize again
        function getConfig() {
          return _configObject;
        }
    
        return {
          initialize: initialize,
          getConfig: getConfig
        }
      }
      ]
    );
    

提交回复
热议问题