无法在Angular JS工厂中访问$ http响应数据

时间:2015-02-26 15:34:33

标签: angularjs angularjs-scope angularjs-service

我正在尝试将$http响应数据保存在angularJS工厂内的变量中。但我无法访问http方法之外的响应。它显示undefined。我查看了这个链接Injecting $scope into an angular service function()请让我知道如何处理这个问题。 以下是工厂代码:



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




1 个答案:

答案 0 :(得分:2)

因为$ http服务是异步的。你应该这样做:

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

})