1

I am new to angular so I need detailed solution to this question. I have seen a lot of answers but not according to my situation.

I have a service:

function ticketService($resource, globals) {
        return $resource(globals.API_URL+'/tickets/:id', {id: '@id'}, {
            update: {method: 'PUT'}
        });
    }

Now I need to cancel previous call when a new call is made. How I need to use timeout parameter here?

In controller im calling this service like this:

ticketService.get({group_by: type}, function(data) {
.
.
.
.
});

How I need to alter my service and controller.

Thanks.

Adnan Ali
  • 2,890
  • 5
  • 29
  • 50

1 Answers1

3

The example is this previous Stackoverflow question should work for what your asking as well. $resource supports the timeout feature Angular has for its promise system.

How to cancel an $http request in AngularJS?

var canceller;

function ticketService($resource, globals) {
    canceller = $q.defer();

    return $resource(globals.API_URL + '/tickets/:id', {
        timeout: canceller.promise,
        id: '@id'
    }, {
        update: {method: 'PUT'}
    });
}

function cancelRequest() {
    if (canceller) {
        // You could also use a $timeout timer to cancel it
        canceller.resolve('cancelled');
    }
}
Community
  • 1
  • 1
Mason Mize
  • 211
  • 1
  • 5
  • alright. One question how we are using cancelRequest() method? – Adnan Ali Apr 01 '15 at 23:51
  • This method could be called anywhere in your controller, you could also add it to the `$scope` so that UI can have a `ng-click` allowing the user to cancel the request. You could also pass `canceller` into a `Service method` for logic to cancel within your custom service. Many options/routes to go – Mason Mize Apr 01 '15 at 23:55
  • @AdnanAli Your welcome, don't forget to accept if you were able to get a working solution. – Mason Mize Apr 02 '15 at 01:00
  • Sorry for digging this up, but the [AngularJS documentation](https://docs.angularjs.org/api/ngResource/service/$resource) strictly states that `In contrast to $http.config, promises are not supported in $resource`. You would have to use `cancellable` and `$cancelRequest` instead. – Gerrit-K Sep 06 '17 at 12:48