Search code examples
angularjsangularjs-scopeangularjs-service

Unable to access $http response data in Angular JS factory


I am trying to save $http response data in a variable inside angularJS factory. But I could not access the response outside the http method. It is showing undefined. I checked this link Injecting $scope into an angular service function() Please let me know how to handle this. Below is the factory code:

angular.module('myapp')
  .factory('CardNumberFactory',['$http', function ($http) {
    // Service logic
    var details={};
  
    $http.get('scripts/services/mock.json')
      .then(function(responce){       
        var resopnceData = responce.data;
            details=resopnceData;
      });

    console.log(details);
    return {details:details};
}]);


Solution

  • Because the $http service is asynchrony. You should do this like that:

    angular.module('myapp')
      .factory('CardNumberFactory',['$http', function ($http) {
    
        var details={};
    
        function getData() {
          return $http.get('scripts/services/mock.json')
           .then(function(response){
             return {details: response.data}
          });      
        }
    
        return {
    
            getData: getData
    
         }
    
    }]);
    
    angular.module('myapp').controller('TestController, function($scope,CardNumberFactory) {
    
      CardNumberFactory.getData().then(function(res) {
          //  res is the {details} object
      })
    
    })