角度承诺响应检查

时间:2015-11-11 23:47:06

标签: javascript angularjs promise

我正在Angular中进行一些http调用,并在发生错误时尝试调用其他服务函数。但是,无论我的原始服务调用函数返回,它返回的承诺始终是" undefined"。以下是一些提供上下文的代码:

  srvc.sendApplicantsToSR = function (applicant) {
    var applicantURL = {snip};

var promise = $http({
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    method: 'POST',
    url: applicantURL,
    data: applicant
})
  .success(function (data) {
    return data;
  })
  .error(function (error) {
    return [];
  });

  return promise;
  };

然后,在控制器中:

for (var applicant in $scope.applicants) {
            $scope.sendATSError($scope.sendApplicantsToSR($scope.applicants[applicant]), applicant);
       }

$scope.sendATSError = function (errorCheck, applicantNumber) {
      if (angular.isUndefined(errorCheck)) {
      console.log(errorCheck);
        AtsintegrationsService.applicantErrorHandling($scope.applicants[applicantNumber].dataset.atsApplicantID);
      }
    };

但是,它总是发送错误,因为每个响应都是未定义的。如何正确区分两种退货?谢谢!

3 个答案:

答案 0 :(得分:3)

查看angular documentation,示例代码为

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

基于此 - 您的第一个代码段应为

 srvc.sendApplicantsToSR = function(applicant) {
     var applicantURL = {
         snip
     };

     return $http({
         headers: {
             'Content-Type': 'application/x-www-form-urlencoded'
         },
         method: 'POST',
         url: applicantURL,
         data: applicant
     });
 };

答案 1 :(得分:2)

您应该将您的promisse返回给控制器本身处理。

简化:

.factory('myFactory', function() {
    return $http.post(...);
})
.controller('ctrl', function(){
    myFactory()
        .success(function(data){
             // this is your data
        })
})

工作示例:



angular.module('myApp',[])
.factory('myName', function($q, $timeout) {
    return function() {
        var deferred = $q.defer();
        $timeout(function() {
            deferred.resolve('Foo');
        }, 2000);
        return deferred.promise;
    }
})
.controller('ctrl', function($scope, myName) {
    $scope.greeting = 'Waiting info.';
    myName().then(function(data) {
       	$scope.greeting = 'Hello '+data+'!';
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="ctrl">
    {{greeting}}!
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:2)

正如其他人所说,$ http的.success().error()已被弃用,转而使用.then()

但实际上您并不需要在.then()中链接.sendApplicantsToSR(),因为您不需要(曾经)处理成功交付的data或处理(此时)不成功的错误。

$scope.sendApplicantsToSR = function (applicant) {
    var applicantURL = {snip};
    return $http({
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        method: 'POST',
        url: applicantURL,
        data: applicant
    });
};

现在,在调用者(for循环中的代码行)中,返回 promise (而非数据),并且该承诺将在解决后继续成功路径或其错误路径。究竟在这些路径上发生的事情完全取决于您在一个或多个链接的.thens中编写的回调函数。

所以你需要写的是一个内部版本的问题 - 外部为$scope.sendApplicantsToSR(),内部为$scope.sendATSError() - 并与{{1}链接在一起}}

.then()

通过传递for (var prop in $scope.applicants) { var applicant = $scope.applicants[prop]; $scope.sendApplicantsToSR(applicant).then(null, $scope.sendATSError.bind(null, applicant)); } // Above, `null` means do nothing on success, and // `function(e) {...}` causes the error to be handled appropriately. // This is the branching you seek!! ,错误处理程序applicant将简化为:

$scope.sendATSError()

你可能想知道的唯一另一件事是所有的承诺都已经解决了,但最好在另一个问题中得到解决。