gpt4 book ai didi

AngularJS : returning data from service to controller

转载 作者:行者123 更新时间:2023-12-04 04:56:58 24 4
gpt4 key购买 nike

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

我的服务:

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

我的家庭 Controller :
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

工厂

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

同样,在 Controller 内部,您应该调用factory函数,并在 .then服务函数解析 getResponders调用并将 $http.get分配给 data时,使用 $scope.gotData函数进行调用。

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

};

关于AngularJS : returning data from service to controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32147907/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com