I have an AngularJS service that I want to initialize with some asynchronous data. Something like this:
myModule.service(\'MyService\', function($http) {
Based on Martin Atkins' solution, here is a complete, concise pure-Angular solution:
(function() {
var initInjector = angular.injector(['ng']);
var $http = initInjector.get('$http');
$http.get('/config.json').then(
function (response) {
angular.module('config', []).constant('CONFIG', response.data);
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});
}
);
})();
This solution uses a self-executing anonymous function to get the $http service, request the config, and inject it into a constant called CONFIG when it becomes available.
Once completely, we wait until the document is ready and then bootstrap the Angular app.
This is a slight enhancement over Martin's solution, which deferred fetching the config until after the document is ready. As far as I know, there is no reason to delay the $http call for that.
Unit Testing
Note: I have discovered this solution does not work well when unit-testing when the code is included in your app.js
file. The reason for this is that the above code runs immediately when the JS file is loaded. This means the test framework (Jasmine in my case) doesn't have a chance to provide a mock implementation of $http
.
My solution, which I'm not completely satisfied with, was to move this code to our index.html
file, so the Grunt/Karma/Jasmine unit test infrastructure does not see it.