0

I'm using the code found from this SO post to cancel my HTTP requests mid-request if they time out:

var canceller = $q.defer();

$timeout(function() {
  canceller.resolve();
  alert("HTTP request failed.");
}, 5000);

$http({
  url: endpoint + "/encode",
  timeout: canceller.promise,
  data: {
    post: posts.post[id]
  }
}).success(successFunction);

However, I keep getting ReferenceError: timeout is not defined in my console. What could I possibly be doing wrong here?

Community
  • 1
  • 1
Someone
  • 428
  • 5
  • 17

1 Answers1

1

So without a plunker it's difficult to replicate but I successfully cancelled a http request using your code for inspiration. Plunker here

Controller.js

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $q, $http, $timeout) {

  $scope.msg = 'Not done it';

  var canceller = $q.defer();

  $scope.doThis = function() {
    $timeout(function() {
      canceller.resolve();
      $scope.msg = "I cancelled it";
    }, 1);

    $scope.msg = "I did it";
    var url = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D%22nome%2C%20ak%22)&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';
    var request = $http.get( url, {timeout: canceller.promise});
    request.success(function(results) {
      $scope.msg = "I loaded some data";
      $scope.data = results;
    });
  }
});

view.html

 <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    <p>{{msg}}</p>
    <a href="" ng-click="doThis()">Do This</a>
    <p>
      {{data}}
    </p>
  </body>
Gene
  • 616
  • 4
  • 8