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

时间:2016-08-19 17:51:08

标签: javascript angularjs algorithm ecmascript-6

我不确定搜索此内容的确切关键字。所以我决定在这里寻求帮助。

我认为这更像是一个与JavaScript相关的问题而非角度。无论如何这是我的问题。

我处于干旱状态(不要重复自己)。我正在尝试合并我的两个 $ http.put $ 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)

但也许有另一种聪明的方法可以做到这一点?

感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

您可以做的是创建自己的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>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

根据您的实际使用情况,这最终可能会牺牲太多的可读性而无法提供帮助,但是因为您专门要求聪明:

UIPopoverPresentationController