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

时间:2015-08-21 19:22:54

标签: angularjs angularjs-service angular-promise angularjs-factory angularjs-http

我正在尝试创建一个服务来获取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);
}]);

2 个答案:

答案 0 :(得分:20)

您应该从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; }); };

<强>代码

all: hello.exe

clean:

--TAB-- rm main.o hello.exe

hello.exe: main.o

--TAB-- g++ -g -o hello main.o

main.o:

--TAB-- g++ -c -g main.cpp

答案 1 :(得分:3)

这是我为我的项目做的一个例子,它适用于我

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

  });