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

查看:47
本文介绍了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 函数返回 promise,&当它得到解决时,它应该从该函数返回 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;
            });
        }
    };
}]);

同样在你的控制器中,你应该调用工厂函数并使用 .then 函数在 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天全站免登陆