我正在尝试创建一个服务来获取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); }]);
你应该从getResponders函数返回promise,&当它得到解决时,它应该从该函数返回response.data.
原文链接:https://www.f2er.com/angularjs/143540.html厂
var myService = angular.module("xo").factory("myService",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调用并将数据分配给$scope.gotData时调用它.
码
$scope.goData = function(){ myService.getResponders.then(function(data){ $scope.gotData = data; }); };