$ http.post()angularjs响应函数没有按正确的顺序执行

时间:2016-04-25 16:36:25

标签: javascript angularjs

从我的角度控制器中,我正在进行函数调用以执行$ http.post()请求。

$scope.formSuccess = false;

$scope.submit = function(serviceName) {
   submitRequest(serviceName);
   if($scope.formSuccess) {
      // do something 
    }
};

var submitRequest = function(serviceName) {
   $http.post(serviceName, data, { headers: { 'Content-type':   'application/json' }  
  }).then(successFunction, errorFunction);
};

var successFunction = function(response) {
  $scope.formSuccess =true;
};

submitRequest()下面的代码首先执行而不是successFunction(),因此if块中的代码永远不会执行。我怎样才能做到这一点。如果阻止成功,我不想移动。

2 个答案:

答案 0 :(得分:2)

问题是这行if($scope.formSuccess) {http请求完成之前执行,因此if内的语句永远不会被执行。

最干净的解决方案是在$http.post成功和失败

上引入要执行的功能



$scope.formSuccess = false;

$scope.submit = function(serviceName) {
   submitRequest(serviceName)
    .then(onPostSuccess)
    .catch(onPostFail);
};

var submitRequest = function(serviceName) {
   return $http.post(serviceName, data, { headers: { 'Content-type':   'application/json' }  
   });
};

var onPostSuccess = function(response) {
  $scope.formSuccess = true;
  //do your stuff here
  
};

var onPostFail = function(response){
  $scope.formSuccess = false;
  //show form failed
}




答案 1 :(得分:1)

因为在提交函数中,如果($ scope.formSuccess)没有等待http响应。所以它总是错误的,你需要把它放在承诺函数中

var successFunction = function(response) {
  $scope.formSuccess =true;
  // do what you want in here

};