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

3
  • 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. Commented Feb 26, 2015 at 15:36
  • andyshora.com/promises-angularjs-explained-as-cartoon.html Commented Feb 26, 2015 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 Commented Feb 26, 2015 at 15:44

1 Answer 1

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

})
Sign up to request clarification or add additional context in comments.

2 Comments

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?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.