Angular JS从服务和Http回调方法返回数据
Angular JS return data from service and Http callback Method
创建了一个 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/空"数据而无需等待$http方法。
问题是,"sendRequest"方法中的调用$http异步的(我的意思是,一旦从服务器获得响应,就会调用"then"),我想等待服务器响应并向调用者发送响应。
你的服务应该是这样的,
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;
});
相关文章:
- Google Data API上的OOP Javascript回调方法
- 与 promise 一起使用时,异步瀑布不执行下一个回调方法
- 传递promise回调方法的更好方法
- meSpeak.js-第二个单词在使用回调方法时不会播放
- 如何将回调方法发送到另一个回调方法
- 如何在 JavaScript 中编写高效的事件回调方法
- 如何在 jquery 中将事件作为回调方法传递
- 有没有办法保证回调方法之外的回调
- 在回调方法中传递动态值
- “(回调方法)未定义”在 Firefox 插件上的 JSONP 访问中
- Javascript在回调方法中编写此上下文
- Javascript回调方法不更新AngularJS,除非是速记形式
- 如何查询回调方法的参数
- Dojo :如何使用回调方法在 jsonRest 存储上发出 PUT 请求
- Angular JS从服务和Http回调方法返回数据
- 描述从回调方法获取正确的作用域
- 如何将参数传递给JQuery$.getJSON回调方法
- 回调方法中未定义RequireJS依赖项
- Node.js和串口;回调方法
- $.post()回调方法建议