0

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};
}]);
Community
  • 1
  • 1
srinivas
  • 109
  • 1
  • 3
  • 14
  • 1
    At the time that you are logging the variable, it is still `undefined`. It only becomes defined inside `.then`, which happens asynchronously some time later. – New Dev Feb 26 '15 at 15:36
  • http://andyshora.com/promises-angularjs-explained-as-cartoon.html – kasoban Feb 26 '15 at 15:41
  • 2
    `return $http.get(..)` instead - this returns a promise - and `.then` it in the controller and assign the return value to your `$scope` – New Dev Feb 26 '15 at 15:44

1 Answers1

2

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
  })

})
Artyom Kiriliyk
  • 2,513
  • 1
  • 17
  • 21
Bazinga
  • 10,716
  • 6
  • 38
  • 63
  • I followed the same way and superb it is working! But i am trying to save the response data in separate global variable to share the data with another controller. How can i do this? – srinivas Feb 26 '15 at 18:08
  • You can inject the factory to any controller that you want and call this function and grab the data or you can make a constant and save the data there, there is many ways. – Bazinga Feb 27 '15 at 07:19