我正面临一个问题。我有angularjs函数,它反过来调用另一个有post请求的angularjs函数。当第一个函数结束时,这个帖子请求总是在最后触发..它不会被触发。
pseudo code
$scope.fun1= function()
{
$scope.fun2();
console.log("after call to fun2"); // execute before fun2
}
$scope.fun2=function()
{
$http.post(valid request);///this always executed at last..means at end of function 1...no matter at what position i call it
}
请有人向我解释这个行为..对此的任何解决方法...我想按顺序执行所有http请求。 提前谢谢!
答案 0 :(得分:1)
您可以使用承诺。一个promise将为您提供一个变量,您可以根据将来发生的某些事件调用注册一段代码 - 在这种情况下,$ http.post()返回。 您可以阅读有关promises here的更多信息,并查看下面修改过的伪代码。
// pseudo code
$scope.fun1= function()
{
$scope.fun2().then(function(data) {
console.log("after call to fun2"); // execute before fun2
});
}
$scope.fun2=function() {
var deferred = $q.defer();
$http({
url: "whatever/something",
method: "POST",
params: {// if you need params}
}).success(function (data) {
deferred.resolve(data);
}).error(function () {
deferred.resolve(null);
});
return deferred.promise;
}
答案 1 :(得分:0)
您正在寻找的是同步通话。虽然使用XmlHttpRequest对象是可能的,但是角度$ http目前还不支持,并且在等待来自服务器的响应时冻结网页被认为是糟糕的编程习惯。如果您希望在帖子后执行控制台日志,您可以将调用结果返回到.post()
并使用.success()
方法在完成后执行某些操作(PLNKR):
var app = angular.module("MyApp", []);
var ctrl = app.controller("MyCtrl", function($scope, $http) {
$scope.fun1 = function() {
$scope.fun2().success(function(data) {
console.log('after call to fun2');
});
};
$scope.fun2 = function() {
var result = $http.get('data.json').success(function(data) {
console.log('fun2 got', JSON.stringify(data));
});
return result; // still has .success() and .error() functions on it
};
})