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 1801
伪装坚强ぢ
伪装坚强ぢ 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:40

    Why don't you initialize the factory when the app is loading and put the variable onto another property? Something like this:

    angular.module('myApp').factory('api', ["$http", "$q",
      function ($http, $q) {
        // store URL in a variable within the factory
        var _URL;
    
        function _initFactory() {
          var deferred = $q.defer();
          $http.get('/scripts/constants/config.json')
          .success(function (data) {
    
            // Set your variable after the data is received
            _URL = data.RESTAPIURL;
            deferred.resolve(data);
    
          });
          return deferred.promise;
        }
    
        function getURL() {
            return _URL;
        }
    
        return {
          initFactory: _initFactory,
          URL: getURL
        }
      }
      ]
    );
    
    
    // While the app is initializing a main controller, or w/e you may do, run initFactory
    //...
    api.initFactory().then(
      // may not need to do this if the URL isn't used during other initialization
    )
    //...
    
    // then to use the variable later
    function _get(creds) {
    
        var deferred = $q.defer();
    
        $http({method: 'GET', url: api.URL + api.AUTH, headers: {
            'Authorization': 'Basic '+creds}
        })
        .success(function (data, status, results, headers) {
            deferred.resolve(results);
        })
        return deferred.promise;
     }
    

提交回复
热议问题