为什么我无法取消此Angular HTTP请求?

时间:2016-04-01 02:42:06

标签: javascript angularjs promise

我使用this SO帖子中的代码,如果他们超时,请在请求中取消我的HTTP请求:

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);

但是,我一直在我的控制台中获取ReferenceError: timeout is not defined。我可能在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

因此,如果没有一个plunker,很难复制,但我使用您的代码成功取消了一个http请求。 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>