javascript
anjularjs ajax 调用,AngularJS AJAX调用的服务(AngularJS Ajax Call in Service
我想我的應(yīng)用程序,使AJAX調(diào)用一個RESTful Web服務(wù)。 在我的html文件是連接到一個范圍對象兩個文本框。 這兩個領(lǐng)域都連接到通過NG-變“后”功能。 post方法發(fā)送“形式”變量從范圍的API和web服務(wù)增加了兩個數(shù)字,并用JSON文件,該文件現(xiàn)在包含的結(jié)果做出響應(yīng)。 (這可能不是很REST風(fēng)格,但它為我的作品)
它只要我在我的控制器這樣的Ajax調(diào)用工作完全正常:
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;
});
};
}]);
現(xiàn)在當(dāng)然不會很好看。 所以,我試圖把Ajax調(diào)用到服務(wù)。
這項新服務(wù)是這樣的:
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;
};
}]);
在控制器我把這樣的服務(wù):
[...]
$scope.post = function($scope.form) {
$scope.form = myService.post($scope.form);
};
[...]
它沒有在所有的工作。 所以我說在服務(wù)這三個警報。 什么時候我在瀏覽器中打開我的應(yīng)用情況是,當(dāng)我改變一個字段,彈出的第一個警告是在一個叫“結(jié)果1”,然后“Result3”,然后“結(jié)果2”。 結(jié)果2甚至可以顯示正確的結(jié)果。 所以,在某種程度上好像在我的服務(wù)“后”功能不等待Ajax調(diào)用來完成。
是否有人知道如何我可能會解決這一問題?
總結(jié)
以上是生活随笔為你收集整理的anjularjs ajax 调用,AngularJS AJAX调用的服务(AngularJS Ajax Call in Service的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如月真绫的诱惑 攻略
- 下一篇: 文件共享服务器第二部,第二章-构建Sam