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 1804
伪装坚强ぢ
伪装坚强ぢ 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:46

    I would pass a callback to the getURL method, and save the URL when it returns. Then I would attach any subsequent requests to that callback. Here I am assuming that you are doing something similar with api.AUTH that you don't have a reference to in your code.

    Pass a callback to the getURL method in the api service.

    angular.module('myApp').factory('api', ["$http", "$q",
    
    function ($http, $q) {
    
        function _getConfiguration() {
            var deferred = $q.defer();
            $http.get('/scripts/constants/config.json')
                .success(function (data) {
                deferred.resolve(data);
            })
                .error(function (data, status) {
                deferred.reject(data, status);
            });
            return deferred.promise;
        }
    
        return {
            getURL: function (cb) {
                var that = this;
                if (that.URL) {
                    return cb(that.URL);
                }
    
                _.getConfiguration().then(function (data) {
                    that.URL = data.config.RESTAPIURL + "/api";
                    cb(that.URL);
                });
            }
        }
    }]);
    

    And in your AuthService, wrap your _get inside a callback like this:

    angular.module('myApp').factory('AuthService', function ($http, $q, api, NotificationService) {
    
        function _get(creds) {
            var deferred = $q.defer();
            var getCallback = function (url) {
    
                $http({
                    method: 'GET',
                    url: url + api.AUTH,
                    headers: {
                        'Authorization': 'Basic ' + creds
                    }
                })
                    .success(function (data, status, results, headers) {
                    deferred.resolve(results);
                })
                    .error(function (data, status) {
                    NotificationService.redirect(status);
                    deferred.reject(data, status);
                });
            };
            api.getURL(getCallback);
            return deferred.promise;
        }
    
        return {
            get: _get
        };
    });
    

提交回复
热议问题