Search code examples
angularjsangularjs-serviceangular-promiseangularjs-resourceangularjs-timeout

Cancel a resource request in angular


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.


Solution

  • 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');
        }
    }