1

I have a ajax call like this

    angular.module('my.module')
    .factory('Users', ['config', '$resource', function(config, $resource) {
      return $resource('/my/endpoint', {
        userId: '@userId'
      }, {
        query: {
            method: "GET"
        }
    });
  }])

then I have a UserLoader

.factory('UserLoader', ['Users', 'LoaderFactory', function(users, LoaderFactory) {
   [some other stuff]
}])

and the the controller

.controller('UserSearchCtrl', ['$scope', 'UserLoader', function($scope, UserLoader) {

}])

how can I cancel a previous call before to send another?

user3174311
  • 1,714
  • 5
  • 28
  • 66

1 Answers1

1

You need to configure your resource as cancellable

query: {method: 'get',cancellable: true}

Then you can call $cancelRequest() on this resource.

Users.query().$cancelRequest()
Andrey
  • 4,020
  • 21
  • 35
  • from my controller? How? – user3174311 Nov 09 '17 at 12:15
  • How do you require and use your factory? Maybe I can help if you share the code – Andrey Nov 09 '17 at 13:25
  • I have another factory called UserLoader, that refers to Users. then userLoader in injected in the controller – user3174311 Nov 09 '17 at 13:56
  • You can return `Users.query()` from `UserLoader` and by doing this you will have access to request object – Andrey Nov 09 '17 at 15:06
  • UserLoader is currently returning an instance of LoaderFactory, how can I embed Users.query()? However, I am able to access Users from the controller adding it in the signature, but calling Users.query().$cancelRequest() gives me non-existing method. Can you provide an example? – user3174311 Nov 09 '17 at 15:52
  • 1
    marked this answer as correct. solution is fine but you need angularjs >= 1.5.4 – user3174311 Nov 15 '17 at 11:19