在AngularJS中使用服务将对象值返回给控制器 [英] Using Services in AngularJS to return object value to controller
问题描述
我正在尝试从JSON文件读取名称.我首先使用唯一的控制器在没有服务的情况下创建服务,但是随后将业务逻辑转移到服务.对于如何将$ scope.mydata从服务返回到控制器,我并不清楚.没有得到任何输出,请帮忙.谢谢.
I am trying to read names from the JSON file. I first created without services using the only controller.But then to moved the business logic to services. I am not getting a clear idea that about how to return the $scope.mydata from service to the controller. Not getting any output please help. Thank you.
<!DOCTYPE html>
<html>
<head>
<title></title>
<!-- Add angularjs -->
<!-- Add controller script-->
<script type="text/javascript">
var app = angular.module('x2js', []);
app.controller('ctrl',
['$scope','myService',function($scope,myService){
$scope.data = function(){
myService.getData()
}
}]);
app.service('myService', ['$http','$log', function($http,$log){
this.getData = function(){
$http({
url:"student.json",
method:"GET",
dataType: 'json',
contentType: "application/json"
}).then(function(response){
$scope.myData = response.data.records;
$log.info($scope.post);
return($scope.myData);
},function(response){
$log.error("Error occured");
});
}
}])
</script>
</head>
<body ng-app="x2js">
<div ng-controller="ctrl">
<table>
<tr>
<td ng-repeat="x in Data">{{x.Name}}</td>
</tr>
</table>
</div>
</body>
</html>
推荐答案
In the service, return the promise created by the .then
method:
app.service('myService', ['$http','$log', function($http,$log){
this.getData = function(){
͟r͟e͟t͟u͟r͟n͟ $http({
url:"student.json",
method:"GET",
//dataType: 'json',
//contentType: "application/json"
}).then(function(response){
var myData = response.data.records;
//$log.info($scope.post);
return(myData);
},function(errorResponse){
$log.error("Error occured "+errorResponse.status);
//IMPORTANT
throw response;
});
}
}])
在控制器中,从promise中提取数据:
In the controller, extract the data from the promise:
app.controller('ctrl',
['$scope','myService',function($scope,myService){
var promise = myService.getData();
promise.then(function(data) {
$scope.data = data;
}).catch(errorResponse) {
console.log(errorResponse,status);
throw errorResponse;
});
}]);
promise的 .then
方法返回一个新的Promise ,该新的Promise通过 successCallback
的返回值进行解析或拒绝.> errorCallback
(除非该值是一个承诺,在这种情况下,使用 1
The .then
method of a promise returns a new promise which is resolved or rejected via the return value of the successCallback
, errorCallback
(unless that value is a promise, in which case it is resolved with the value which is resolved in that promise using promise chaining.1
在promise错误处理程序中,重要的是重新抛出错误响应,否则被拒绝的promise将被转换为已实现的promise,并返回 undefined
的值.
In promise error handlers, it is important to re-throw the error response otherwise the rejected promise will be converted to a fulfilled promise that returns a value of undefined
.
这篇关于在AngularJS中使用服务将对象值返回给控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!