ajax - Angular.js $http 请求后,无论promise成功还是失败,都调用完整的函数

标签 ajax angularjs promise

我怎样才能确保complete()无论使用 Angular.js 提供的 promise API 调用 $http 的结果如何,函数都会运行吗?

$http({
    method: 'POST',
    url: submitUrl,
    data: $scope.data
})
.success(function(data) {
      // execute this code on success
})
.error(function(data) {
      // execute this code on error
})
.complete(function() {
  // execute this code regardless of outcome
});

一旦请求完成,人们可以使用它来隐藏 AJAX 微调器图标。无论请求结果如何,您都希望隐藏微调器。

最佳答案

我不是 Angular.js 世界上最伟大的专家,但我知道你可以这样做:

whatever.then(function() {
    // success code here
}, function() {
    // error code here
    return true; // return anything that's not undefined (and not a `throw()`) to force the chain down the success path at the following then().
}).then(function() {
    // "complete" code here
});

您基本上被迫从一个或多个 .then() 中设计出一些东西,这是 $q promise 的唯一方法。

关于ajax - Angular.js $http 请求后,无论promise成功还是失败,都调用完整的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17181508/

相关文章:

php - 这是合法的长轮询方法吗?

jquery - 如何使用多个按钮修复 Ajax 提交中的未验证错误 token laravel

php - 如何限制用户在没有特定操作(例如,单击提交按钮)的情况下离开页面

angularjs - 从 JWT token 检索 Azure 组详细信息

angularjs - ui-router 在父状态解析之前触发子状态

javascript - ionic 模式无法打开

javascript - NodeJS : Functional Programming - No access to prototype in handover function

javascript - innerHTML 的替代品

javascript - 将 Array.map() 的结果添加到一个数组中

javascript - 从另一个 promise 中的 promise 返回值