Assume the following AngularJS service factory:
function Constants($http) {
var constants = {
someFields: someValues
};
$http({method: "GET", url: baseUrl + "/constants.json"}).success(
function (data, status) {
angular.forEach(data, function (value, key) {
constants[key] = value;
});
}
);
return constants;
}
It creates a service Constants
with a set of constants in there. The constants are partly hardcoded and partly loaded from the constants.json
, located on server (this logic is not discussable). This service is then used in a controller:
function SettingsController($scope, $rootScope, Constants) {
$scope.someProperty = Constants.somePropertyFromConstantsJson;
...
I understand that $http
calls are asynchronous. It means that there is no guarantee that the properties from constants.json
in the example will be loaded and put to Constants
before they are read in SettingsController
.
How could I provide such a guarantee? How could I make SettingsController
initialized only after the $http
call in Constants
is over?
UPD: The case I am talking about is a part of a bigger project. I want to avoid bigger changes all over the code base, so I need Constants
to remain an object, properties of which are accessible through .
or []
. That's why I'll consider options which doesn't fit this desire as a last resort.
UPD2: I checked the question marked as duplicate. Actually, I understand that $http
is asynchronous operation, and I don't have intention to extract the local state of callbacks to the Constants
factory constructor. The code of Constants
constructor does that, but I am ok with refactoring it (until the type of Constants
service and its properties is kept). I just wanted a way to make Angular create Constants
service after the Http call is done. Some sort of asynchronous service initialization. I think my desire doesn't contradict with async nature of stuff, correct me please if I am wrong.