AngularJS : 从服务返回数据到控制器

AngularJS : returning data from service to controller

我正在尝试创建一个服务来获取 json 并将其传递给我的 homeCtrl 我可以获取数据但是当将它传递给我的 homeCtrl 时它总是 returns 未定义。我卡住了。

我的服务:

var myService = angular.module("xo").factory("myService", ['$http', function($http){
  return{
    getResponders: (function(response){
      $http.get('myUrl').then(function(response){
         console.log("coming from servicejs", response.data);
      });
    })()
  };
  return myService;
  }
]);

我的家庭控制器:

var homeCtrl = angular.module("xo").controller("homeCtrl", ["$rootScope", "$scope", "$http", "myService",
function ($rootScope, $scope, $http, myService) {
 $scope.goData = function(){
     $scope.gotData = myService.getResponders;
 };
 console.log("my service is running", $scope.goData, myService);
}]);

你应该 return 从 getResponders 函数中承诺,并且当它得到解决时它应该 return response.data 从那个函数中。

工厂

var myService = angular.module("xo").factory("myService", ['$http', function($http) {
    return {
        getResponders: function() {    
            return $http.get('myUrl')
            .then(function(response) {
                console.log("coming from servicejs", response.data);
                //return data when promise resolved
                //that would help you to continue promise chain.
                return response.data;
            });
        }
    };
}]);

同样在你的控制器中,你应该调用工厂函数并使用 .then 函数在 getResponders 服务函数解析 $http.get 调用时调用它并分配 data$scope.gotData

代码

 $scope.goData = function(){
     myService.getResponders.then(function(data){
          $scope.gotData = data;
     });

 };

这是我为我的项目做的一个例子,对我来说效果很好

var biblionum = angular.module('biblioApp', []);//your app
biblionum.service('CategorieService', function($http) {


    this.getAll = function() {

        return $http({
            method: 'GET',
            url: 'ouvrage?action=getcategorie',
            // pass in data as strings
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}  // set the headers so angular passing info as form data (not request payload)
        })
                .then(function(data) {

                    return data;


                })


    }


});

biblionum.controller('libraryController', function($scope,CategorieService) {
  
    var cat = CategorieService.getAll();
    cat.then(function(data) {
        $scope.categories = data.data;//don't forget "this" in the service
    })

  });