如何取消1.5中angularjs中$ resource的承诺

时间:2016-08-10 05:50:06

标签: javascript angularjs

我正在使用angular 1.5.7,如果需要时间,我想取消对资源的删除。我正在使用MEAN堆栈,有时我看到我的资源上的删除被视为待处理(是mongo哪个很慢?)。 下面是工厂和控制器的片段,我称之为删除: *工厂:

      .factory('addressesFactory', ['$resource', 'baseURL', function ($resource, baseURL) {
    return $resource(baseURL + 'addresses/:id', {id: '@_id'}, {
      'update': {
        method: 'PUT'
      },
      'delete': {
        method: 'DELETE'
      }
    });
  }])
  • 来自控制器的片段:

    $scope.delete = function (address, addressesList) {
    
    $scope.deleteDisabled=true;
    
    console.log('[ModeratorsCtrl] Deleting:' + address.name);
    console.log('[ModeratorsCtrl] ' + addressesList.length);
    addressesFactory.delete({id: address._id}).$promise.then(
      function (response) {
        $scope.deleteDisabled=false;
        console.log('[ModeratorsCtrl] Address deleted successfully');
      },
      function (response) {
        $scope.deleteDisabled=false;
        var message = '[ModeratorsCtrl] Error: ' + response.status + ' ' + response.statusText;
        console.log(message);
      }
    );
    

    };

我看过这篇文章How to cancel $resource requests,并阅读了有关取消请求的信息:https://docs.angularjs.org/api/ngResource/service/ $ resource#!与$ cancelRequest(),但我有点困惑。 任何人都可以给我一些关于我如何在实施中取消承诺的最佳实践吗? 的问候,

2 个答案:

答案 0 :(得分:1)

假设您的资源是Users,要取消请求,您应该为您的行为命名,例如

var request = Users.query();

此时```请求是一个承诺。你可以简单地做一个,

request.$cancelRequest();

取消。

答案 1 :(得分:0)

感谢您的帮助 最后我在工厂做了以下事情:

  .factory('addressesFactory', ['$resource', 'baseURL', function ($resource, baseURL) {
    return $resource(baseURL + 'addresses/:id', {id: '@_id'}, {
      'update': {
        method: 'PUT'
      },
      'delete': {
        method: 'DELETE',
        cancellable: true
      }
    });
  }])

然后在我的控制器中:

 $scope.delete = function (address, addressesList) {
    $scope.deleteDisabled = true;//prevent multiple click

    var deleteRequest = addressesFactory.delete({id: address._id});
    deleteRequest.$promise.then(
      function (response) {
        $scope.deleteDisabled = false;
        console.log('[ModeratorsCtrl] Address deleted successfully');
      },
      function (response) {
        $scope.deleteDisabled = false;
        var message = '[ModeratorsCtrl] Error: ' + response.status + ' ' + response.statusText;
        console.log(message);
      }
    );

    $timeout(function () {//2 seconds then cancel the promise
      if ($scope.deleteDisabled === true) {
        console.log('[ModeratorsCtrl] Cancel ...');
        deleteRequest.$cancelRequest();
        $scope.deleteDisabled = false;
      }
    }, 2000);
  };

希望这符合最佳做法,随时提供反馈。