tuxmobil
tuxmobil

Reputation: 308

how to cancel a promise with $resource in angularjs in 1.5

I'm using angular 1.5.7 and would like to cancel a delete on a resource if it takes time. I'm using a MEAN stack and sometimes I see the delete on my resource seen as pending (is it mongo which is slow ?). Below is the factory and the snippet from the controller where I call the delete: * the factory:

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

I saw this post How to cancel $resource requests and read this about cancelling requests: https://docs.angularjs.org/api/ngResource/service/$resource#! with $cancelRequest() but I'm a bit confused. Can anyone give me the best practices on how I can cancel a promise in my implementation ? Regards,

Upvotes: 1

Views: 1046

Answers (2)

tuxmobil
tuxmobil

Reputation: 308

thanks for the help I ended up by doing the following in my factory:

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

then this in my controller:

 $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);
  };

Hope this sticks to the best practices, feel free to give your feed back.

Upvotes: 0

Yousuf Jawwad
Yousuf Jawwad

Reputation: 3097

lets say your resource is Users, to cancel the request, you should name your action e.g

var request = Users.query();

at this point ```request is a promise. you can simply do a,

request.$cancelRequest();

to cancel.

Upvotes: 1

Related Questions