Tuesday 30 May 2017

javascript - Initialize AngularJS Constant using $http.get call response

The result of $http.get isn't available while the app is initialized. It is only available when the server delivers it. For this reason simply keeping that value in a module constant is impossible. You run the risk of


What you can do however, is wrap the call to $http.get in a service and inject that service wherever you want the constant. (Note that services can't be injected in config blocks.)


// grab the "constant"
angular.module('A').factory('almostConstant', function () {
return $http.get('url').then(function(response) {
return response.data;
});
});
// use the "constant"
angular.module('A').controller('controller', function($scope, almostConstant) {
almostConstant.then(function(data){
$scope.almostConstant = data;
});
});

The slightly awkward mode to access the value of your almostConstant is due to its asynchronous nature. It simply is available at an unspecified time so trying to access it in a synchronous manner can introduce a lot of subtle timing bugs.




A very non angular-ish way of doing this would be to write your constant in the JS file directly. At the moment your server can answer to a request to 'url' with a value. Instead, you could make it answer to a request to 'url.js' with the following string:


angular.module('A').constant('theConstant', result);

where result is obviously your constant. For example if you were using php on the backend it could look something like this:


   header('Content-Type: application/javascript');
$constant = retrieveMyConstant();
?>
angular.module('A').constant('theConstant', );

Make sure that the constant actually looks like a JavaScript value. If it's a string, wrap it in ', if it's a JSON object write its serialization, etc.


After this you simply include a script tag pointing to url.js in your index.html file.


Note that this solution is synchronous, so if retrieving the constant on the server takes a while, it will affect your page load time.

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...