0

I have a service called SuperFactory. This service has a fetch method which pulls some data from a URL.

This service is used by the SuperController

In my controller, how can I cancel this HTTP request (promise) while it's running?

This is my SuperFactory.js

angular
 .module('app')
 .factory('SuperFactory', FetchData)

function SuperFactory($http, $q, $timeout) {
  return {
    fetch: function(name, limit) {
      var fullURL = "http://example.com?id=5;

      var defer = $q.defer();

      var timeoutPromise = $timeout(function() {
        console.log("Timed out");
        defer.reject("Timed out"); //reject the service in case of timeout
      }, 10000);

      var promise = $http.get(fullURL).
      then(function(response) {

        $timeout.cancel(timeoutPromise); //cancel the timeout
        //response = cleanUpResponse(response);
        response = response.data;
        defer.resolve(response);

        return response;
      }, function(response) {
        return 0;
      });

      return defer.promise;
    }
  };
}

This is my SuperController.js

angular
  .module('app')
  .controller('SuperController', SuperController)

function SuperController($scope, SuperFactory, $q, $timeout, $http) {

  SuperFactory.fetch()
    .then(function(data) {
      console.log(data);
    }, function(error) {
      // promise rejected
    });
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
wiseindy
  • 19,434
  • 5
  • 27
  • 38
  • [Avoid the deferred antipattern!](http://stackoverflow.com/q/23803743/1048572) – Bergi Jun 14 '16 at 14:18
  • 2
    Is this what you're looking for: http://stackoverflow.com/questions/13928057/how-to-cancel-an-http-request-in-angularjs – Alexander Kravets Jun 14 '16 at 14:21
  • You might be interested in [How to use $q's constructor syntax with Angular $http's config.timeout?](http://stackoverflow.com/q/36165800/1048572) – Bergi Jun 14 '16 at 14:22

0 Answers0