一尘不染

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

angularjs

我试图创建一个服务来获取json并将其传递给我homeCtrl我可以获取数据,但是当将其传递给我的homeCtrl时,它总是返回undefined。我卡住了。

我的服务:

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

阅读 209

收藏
2020-07-04

共1个答案

一尘不染

您应该从getResponders函数返回promise ,当它被解析后,它应该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;
            });
        }
    };
}]);

同样在控制器内部,您应该调用factory函数,并.thengetRespondersservice函数解析该$http.get调用并将其分配data$scope.gotData

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

 };
2020-07-04