javascript
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調用來完成。
是否有人知道如何我可能會解決這一問題?
總結
以上是生活随笔為你收集整理的anjularjs ajax 调用,AngularJS AJAX调用的服务(AngularJS Ajax Call in Service的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如月真绫的诱惑 攻略
- 下一篇: js template换行_JavaSc