Angular.js Factory: Handling $http Asynchronously

February 20, 2015

The Problem:

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

myApp.factory('myFactory', function($http) {
  var data = { anArray: [] };

  $http.get('/api').success(function(response) {
    data.anArray.push(response);
  });

  return data;
});

This issue arises because the return statement is executed before the $http GET request finishes pushing data into the array.

My Solution:

To handle data asynchronously, the controller needs to instruct the service on what actions to take 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(response, status) {
    $scope.data = response;
  };

  myFactory.getData().success(handleSuccess);
}]);

Let me know if you have any questions. 😊


Profile picture

Software development professional with expertise in application architecture, cloud solutions deployment, and financial products development. Possess a Master's degree in Computer Science and an MBA in Finance. Highly skilled in AWS (Certified Solutions Architect, Developer and SysOps Administrator), GCP (Professional Cloud Architect), Microsoft Azure, Kubernetes(CKA, CKAD, CKS, KCNA), and Scrum(PSM, PSPO) methodologies. Happy to connect