天天看点

anjularjs ajax 调用,AngularJS AJAX调用的服务(AngularJS Ajax Call in Service

我想我的应用程序,使AJAX调用一个RESTful Web服务。 在我的html文件是连接到一个范围对象两个文本框。 这两个领域都连接到通过NG-变“后”功能。 post方法发送“形式”变量从范围的API和web服务增加了两个数字,并用JSON文件,该文件现在包含的结果做出响应。 (这可能不是很REST风格,但它为我的作品)

它只要我在我的控制器这样的Ajax调用工作完全正常:

myApp.controller('myCtrl', ['$scope', '$http', function ($scope, $http) {

$scope.form = {

"number1" : "",

"number2" : "",

"result" : ""

};

$scope.post = function () {

$http({

url: "http://localhost:7777/api",

method: "POST",

data: $scope.form,

headers: {'Content-Type': 'application/json'}

}).success(function (data, status, headers, config) {

$scope.form = data;

}).error(function (data, status, headers, config) {

$scope.status = status;

});

};

}]);

现在当然不会很好看。 所以,我试图把Ajax调用到服务。

这项新服务是这样的:

myApp.service('myService', ['$http', function ($http) {

this.post = function (scopeData) {

var myData = scopeData;

alert('Result1: ' + myData.result);

$http({

url: "http://localhost:7777/api",

method: "POST",

data: myData,

headers: {'Content-Type': 'application/json'}

}).success(function (data, status, headers, config) {

myData = data;

alert('Result2: ' + myData.result);

}).error(function (data, status, headers, config) {

var status = status;

});

};

alert('Result3: ' + myData.result);

return myData;

};

}]);

在控制器我把这样的服务:

[...]

$scope.post = function($scope.form) {

$scope.form = myService.post($scope.form);

};

[...]

它没有在所有的工作。 所以我说在服务这三个警报。 什么时候我在浏览器中打开我的应用情况是,当我改变一个字段,弹出的第一个警告是在一个叫“结果1”,然后“Result3”,然后“结果2”。 结果2甚至可以显示正确的结果。 所以,在某种程度上好像在我的服务“后”功能不等待Ajax调用来完成。

是否有人知道如何我可能会解决这一问题?