我们可以将 $http 注入 Angular 服务并将该数据传递给控制器​​吗?

Can we inject $http in to a Angular Service and pass that data to a controller?

我正在尝试使用 AngularJS 中的服务从外部文件加载 JSON 数据。

myApp.service('ContactsListService', function($http) {
    var contactsList = $http.get('js/contacts.json').success(function(data){
    return data;
    });
    console.log(contactsList); // prints some $http object 
    return {
    'contactsList': contactsList;
    };
}

myApp.controller('ContactDisplayController',['$scope','ContactsListService',function($scope, ContactsListService){
$scope.contacts = ContactsListService.contactsList;
console.log(ContactsListService.contactsList); // prints 'undefined' here
}]);

**JSON file:**

        [
          {
            name: 'Steph Curry',
            mobile: '111111111'
          },
          {
           name: 'Lebron James',
           mobile: '2323232323'
         }
     ]

我想在控制器中使用来自服务的数据,但我无法传递该数据。如果我以错误的方式注入服务,请纠正我。

谢谢!

您存储的是 $http 承诺,而不是 ajax 调用的响应。更好的方法是让服务定义返回承诺的方法,并让您的控制器获得该承诺并使用结果。

myApp.service('ContactsListService', function($http) {
  this.getContactsList = function() {
    return $http.get('js/contacts.json');
  };
});

myApp.controller('ContactDisplayController',['$scope','ContactsListService',function($scope, ContactsListService){
  ContactsListService.getContactsList().success(function(data) {
    $scope.contacts = data;
  });
}]);

感谢Joey的回答,我已经按照你的方法试过了,我无法在成功函数之外打印数据:

myApp.controller('ContactDisplayController',['$scope','ContactsListService',function($scope, ContactsListService){
  ContactsListService.getContactsList().success(function(data) {
    $scope.contacts = data;
   console.log($scope.contacts); // prints data here.
  });
console.log($scope.contacts); // prints undefined here.
}]);

只需要知道这是怎么回事。获取数据,然后对其进行处理,就在处理该数据的过程中。

myApp.controller('ContactDisplayController',['$scope','ContactsListService',function($scope, ContactsListService){
     $scope.contacts = [];  //initialize it
      ContactsListService.getContactsList().success(function(data) {
        $scope.contacts = data;
         //now do stuff with it
      });
     //console logging here happens before your async call returns
    }]);