创建一个Angular JS服务,该服务向服务器发送JSON数据请求。我能够在服务中正确接收数据,但我无法将数据返回给控制器。请检查如下:
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>
Full Name: {{firstName + " " + lastName}}
<br><br><br><br><br><br><br><br><br>
<p>The content is {{content}}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.service('MyService', function($http) {
this.sendRequest = function() {
$http({
method: 'GET',
url: 'http://localhost:3000/json'
}).then(
function successCallback(response) {
console.dir('This is the response');
console.dir(response);
return response;
}, function errorCallback(response) {
console.dir('This is the error');
console.dir(response);
return response;
}
);
};
this.addition = function(a,b) {
return a+b;
};
});
app.controller('myCtrl', function($scope, MyService) {
$scope.firstName = "John";
$scope.lastName = "Doe";
console.dir(MyService.addition(4,5));
var a = MyService.sendRequest();
console.dir("Main program " + a);
$scope.content = a;
});
</script>
</body>
</html>
对于加法函数,我能够正确获取数据(我的意思是它返回4 + 5的总和),但是进入“sendRequest”方法,它正在调用此方法中的$ http调用并获取回到调用者“null / empty”数据而不等待$ http方法。
问题是,“sendRequest”方法中的$ http调用是异步的(我的意思是,一旦从服务器获得响应就会调用“then”)并且我想等待服务器响应并将响应发送到呼叫者。
答案 0 :(得分:1)
您的服务应该是这样的,
app.service('MyService', function($http) {
this.sendRequest = function() {
// You should return $http's result
// $http will return a promise
return $http({
method: 'GET',
url: 'http://localhost:3000/json'
}).then(
function successCallback(response) {
console.dir('This is the response');
console.dir(response);
return response.data;
}, function errorCallback(response) {
console.dir('This is the error');
console.dir(response);
return response;
}
);
};
this.addition = function(a,b) {
return a+b;
};
});
现在像这样修改你的控制器,
app.controller('myCtrl', function($scope, MyService) {
$scope.firstName = "John";
$scope.lastName = "Doe";
console.dir(MyService.addition(4,5));
MyService.sendRequest().then(function success(data){
// here you will get your server data
var a = data;
}, function error(){
});
console.dir("Main program " + a);
$scope.content = a;
});