如何使用AngularJS進行$ http同步調用對不起,我的新手問題,但AngularJS文檔不是非常明確或廣泛,以找出一些基本的東西。有沒有辦法與AngularJS進行同步調用?在服務上:myService.getByID = function (id) {
var retval = null;
$http({
url: "/CO/api/products/" + id,
method: "GET"
}).success(function (data, status, headers, config) {
retval = data.Data;
});
return retval;}
3 回答
哆啦的時光機
TA貢獻1779條經驗 獲得超6個贊
不是現在。如果查看源代碼(從2012年10月的時間點開始),您將看到對XHR open的調用實際上是硬編碼為異步(第三個參數為true):
xhr.open(method, url, true);
您需要編寫自己的同步調用服務。一般情況下,由于JavaScript執行的性質,您通常不會想要這樣做,因此最終會阻止其他所有內容。
...但是......如果實際上需要阻止其他所有內容,也許你應該查看promises和$ q服務。它允許您等待一組異步操作完成,然后在它們全部完成后執行。我不知道你的用例是什么,但這可能值得一看。
除此之外,如果您打算自己動手,可以在此處找到有關如何進行同步和異步ajax調用的更多信息。
我希望這是有幫助的。
犯罪嫌疑人X
TA貢獻2080條經驗 獲得超4個贊
var EmployeeController = ["$scope", "EmployeeService",
function ($scope, EmployeeService) {
$scope.Employee = {};
$scope.Save = function (Employee) {
if ($scope.EmployeeForm.$valid) {
EmployeeService
.Save(Employee)
.then(function (response) {
if (response.HasError) {
$scope.HasError = response.HasError;
$scope.ErrorMessage = response.ResponseMessage;
} else {
}
})
.catch(function (response) {
});
}
}
}]var EmployeeService = ["$http", "$q",
function ($http, $q) {
var self = this;
self.Save = function (employee) {
var deferred = $q.defer();
$http .post("/api/EmployeeApi/Create", angular.toJson(employee))
.success(function (response, status, headers, config) {
deferred.resolve(response, status, headers, config);
})
.error(function (response, status, headers, config) {
deferred.reject(response, status, headers, config);
});
return deferred.promise;
};- 3 回答
- 0 關注
- 670 瀏覽
添加回答
舉報
0/150
提交
取消
