为什么可以't我取消了这个Angular HTTP请求

Why can't I cancel this Angular HTTP request?

本文关键字:Angular 请求 HTTP 取消 为什么      更新时间:2023-10-29

如果HTTP请求超时,我将使用从这篇SO文章中找到的代码在请求中期取消它们:

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。我在这里可能做错了什么?

因此,如果没有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>