如何使用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 关注
- 693 浏览
添加回答
举报
0/150
提交
取消
