Angular会对不同的$http请求应用相同的成功和错误函数体

Angular apply same success and error function bodies to different $http requests

本文关键字:成功 函数体 错误 应用 http Angular 请求      更新时间:2023-09-26

我不确定搜索这个的确切关键字。所以我决定向这里寻求帮助。

我认为这更多的是一个JavaScript相关的问题而不是angular。总之,这是我的问题。

我在DRY的情况下(不要重复你自己)。我试图合并我的两个$http。把$http.delete方法的成功和错误函数放在一个下,因为它们共享相同的功能。

这是我当前的代码

// Delete permanenty button action
  $scope.delete_donor = function(form) {
    $http.delete(url)
      .success(function() {
        // @TODO DRY? DELETE UPDATE delete_donor update_donor
        response.ipv4 = INT_TO_STR_IP(response.ipv4)
        // Show deleted data to user after operation
        $scope.donor.saved_data = response.saved_data
        $location.path("/")
      })
      .error(function(response) {
        $scope.donor.validation_errors = SERVER_VALIDATION_ERROR(response)
      })
  }
  // Save changes button action
  $scope.update_donor = function(form) {
    var body = $scope.donor.data
    delete body.ipv4
    $http.put(url, body)
      .success(function(response) {
        // @TODO DRY? DELETE UPDATE delete_donor update_donor
        response.ipv4 = INT_TO_STR_IP(response.ipv4)
        // Show new updated data to user after operation
        $scope.donor.saved_data = response.saved_data
        $location.path("/")
      })
      .error(function(response) {
        $scope.donor.validation_errors = SERVER_VALIDATION_ERROR(response)
      })

可以看到$http.delete().success().error()和$http.put().success().error()方法是相同的。

我正在尝试做一些像

WHATSTHIS unify(response) {
  WOOT .success(function(response) { // SAME CODE BODY })
  WOOT .error(function(response) { // SAME CODE BODY })
}
// Delete permanenty button action
  $scope.delete_donor = function(form) {
    $http.delete(url)
      .unify(response)
  }
  // Save changes button action
  $scope.update_donor = function(form) {
    var body = $scope.donor.data
    delete body.ipv4
    $http.put(url, body)
      .unify(response)

我只知道一种方法可以达到类似的效果,那就是:

var unifySuccess = function(response) {
  // DO
}
var unifySuccess = function(response) {
  // DO
}
// Delete permanenty button action
  $scope.delete_donor = function(form) {
    $http.delete(url)
      .sucesss(unifySuccess)
      .error(unifyError)

但也许有其他聪明的方法来做到这一点?

谢谢你的帮助。

你可以创建自己的HTTP请求服务来完成这些功能,并返回承诺作为响应

像这样的

angular.module('myApp')
  .service('proxyHttp', function($http) {
    return function(options) {
      return $http(options)
        .then(
          function() {
            // success callback
          },
          function() {
            // error callback
          });
    }
  })

更新:例如

angular.module('myApp', [])
  .service('proxyHttp', function($http, $q) {
    return function(options) {
      console.log('Run proxy http');
      return $http(options)
        .then(
          function(response, status) {
            console.log('always do this on success');
            // success callback
            return response;
            // here we return the response or what ever you want,
            // and we can continue handling it
          })
        .catch(function() {
          console.log('we failed!');
          // error callback
          return $q.reject();
        })
    }
  })
  .controller('testController', function($scope, proxyHttp) {
    $scope.testError = function() {
      console.log('Run test error method');
      proxyHttp({
          url: 'http://www.google.com',
          method: 'GET'
        })
        .then(
          function() {})
        .catch(function() {
          console.log('we continue handling our error here...');
        });
    }
    $scope.testSuccess = function() {
      console.log('Run test success method');
      proxyHttp({
          url: 'http://httpbin.org/ip',
          method: 'GET'
        })
        .then(
          function(response) {
            console.log('continue chaining after success for the original promise');
            console.log('Response data: '
              response.data.origin);
            console.log('read more about pomise and chaining here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise');
          })
        .catch(function() {
          console.log('error');
        });
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
  <div ng-controller="testController">
    <button ng-click="testError()">Click Me for error!</button>
    <br/>
    <br/>
    <button ng-click="testSuccess()">Click Me for success!</button>
  </div>
</div>

根据您的实际用例,这可能最终会牺牲太多的可读性,但由于您特别要求聪明:

function attachHttpResponseHandling(httpPromise) {
    httpPromise
        .success(function(response) {
            response.ipv4 = INT_TO_STR_IP(response.ipv4);
            // Show new updated data to user after operation
            $scope.donor.saved_data = response.saved_data;
            $location.path("/");
        })
        .error(function(response) {
            $scope.donor.validation_errors = SERVER_VALIDATION_ERROR(response);
        })
    ;
}
// Delete permanenty button action
$scope.delete_donor = function(form) {
    attachHttpResponseHandling($http.delete(url));
};
// Save changes button action
$scope.update_donor = function(form) {
    var body = $scope.donor.data;
    delete body.ipv4;
    attachHttpResponseHandling($http.put(url, body));
};