AngularJS:将数据从服务返回到控制器 [英] AngularJS : returning data from service to controller

查看:85
本文介绍了AngularJS:将数据从服务返回到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to create a service to get json and pass it to me homeCtrl I can get the data but when a pass it to my homeCtrl it always returns undefined. Im stuck.

我的服务:

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

推荐答案

您应该从getResponders函数&解决后,应从该函数返回response.data.

You should return promise from getResponders function, & when it gets resolved it should return response.data from that function.

工厂

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

还应该在控制器内部调用工厂函数,并在getResponders服务函数解析$http.get调用并将data分配给$scope.gotData

Also inside your controller you should call the factory function and use .then function to get call it when the getResponders service function resolves the $http.get call and assign the data to $scope.gotData

代码

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

 };

这篇关于AngularJS:将数据从服务返回到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆