Angular.js factory: Handle $http asynchronously

The problem:

When I was using $http service to get data from a remote API, my code below was not able to return data back to the controller.

myApp.factory('myFactory', function($http){ 
var data = { anArray:[] };
  $http.get('/api').success(function(data) { 
data.anArray.push(data);
});
  return data; 
});

This is because the return data is already executed before the $http get request finish pushing data into the array.

My solution:

In order to handle data asynchronously, the controller needs to tell the service what to do when the data is received later:

myApp.factory('myFactory', function($http){ 
return {
getData: function(){
return $http.get('/api');
} };
});
myApp.controller('MyController', ['$scope', 'myFactory', function($scope, myFactory) { 
$scope.data = [];
  var handleSuccess = function(data, status){ 
$scope.data = data;
};
  myFactory.getData().success(handleSuccess); 
}

Let me know if you have any questions ☺


Originally published at victorleungtw.com on December 27, 2014.

By Victor Leung

Experience in software development, consulting services and technical product management. Understanding of business and technology with an MBA in Finance and a Master degree in Computer Science. AWS Certified Solution Architect with experience in building products from scratch and serving as a charismatic leader.

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.