Victor Leung
Victor Leung
BlogAI SolutionAlphaAlgoFlower shopFX CombineIEESushi ClassifierWealth Agile

Angular.js factory: Handle $http asynchronously

February 20, 2015

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 ☺


About Victor Leung

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
LinkedIn
Github
Twitter
@victorleungtw

Continuous improvement

Copyright © victorleungtw.com 2023.