I have an AngularJS service that I want to initialize with some asynchronous data. Something like this:
myModule.service(\'MyService\', function($http) {
What you can do is in your .config for the app is create the resolve object for the route and in the function pass in $q (promise object) and the name of the service you're depending on, and resolve the promise in the callback function for the $http in the service like so:
ROUTE CONFIG
app.config(function($routeProvider){
$routeProvider
.when('/',{
templateUrl: 'home.html',
controller: 'homeCtrl',
resolve:function($q,MyService) {
//create the defer variable and pass it to our service
var defer = $q.defer();
MyService.fetchData(defer);
//this will only return when the promise
//has been resolved. MyService is going to
//do that for us
return defer.promise;
}
})
}
Angular won't render the template or make the controller available until defer.resolve() has been called. We can do that in our service:
SERVICE
app.service('MyService',function($http){
var MyService = {};
//our service accepts a promise object which
//it will resolve on behalf of the calling function
MyService.fetchData = function(q) {
$http({method:'GET',url:'data.php'}).success(function(data){
MyService.data = data;
//when the following is called it will
//release the calling function. in this
//case it's the resolve function in our
//route config
q.resolve();
}
}
return MyService;
});
Now that MyService has the data assigned to it's data property, and the promise in the route resolve object has been resolved, our controller for the route kicks into life, and we can assign the data from the service to our controller object.
CONTROLLER
app.controller('homeCtrl',function($scope,MyService){
$scope.servicedata = MyService.data;
});
Now all our binding in the scope of the controller will be able to use the data which originated from MyService.