如何使用AngularJS進行$ http同步調(diào)用對不起,我的新手問題,但AngularJS文檔不是非常明確或廣泛,以找出一些基本的東西。有沒有辦法與AngularJS進行同步調(diào)用?在服務(wù)上: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 回答

慕婉清6462132
TA貢獻1804條經(jīng)驗 獲得超2個贊
不是現(xiàn)在。如果查看源代碼(從2012年10月的時間點開始),您將看到對XHR open的調(diào)用實際上是硬編碼為異步(第三個參數(shù)為true):
xhr.open(method, url, true);
您需要編寫自己的同步調(diào)用服務(wù)。一般情況下,由于JavaScript執(zhí)行的性質(zhì),您通常不會想要這樣做,因此最終會阻止其他所有內(nèi)容。
...但是......如果實際上需要阻止其他所有內(nèi)容,也許你應(yīng)該查看promises和$ q服務(wù)。它允許您等待一組異步操作完成,然后在它們?nèi)客瓿珊髨?zhí)行。我不知道你的用例是什么,但這可能值得一看。
除此之外,如果您打算自己動手,可以在此處找到有關(guān)如何進行同步和異步ajax調(diào)用的更多信息。
我希望這是有幫助的。

UYOU
TA貢獻1878條經(jīng)驗 獲得超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 關(guān)注
- 837 瀏覽
添加回答
舉報
0/150
提交
取消