2016-04-01 5 views
0
は、私はSO彼らはタイムアウトた場合、私のHTTPリクエスト半ば要求をキャンセルする投稿 thisから見つかったコードを使用してい

このAngular 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を得続けます。私はおそらく何がここで間違っていることができますか?

+0

は、あなたの実際のコードは '$'を欠如していますか?スタックトレースは何を言っていますか、どの行が例外をスローしますか? – Bergi

+0

いいえ、それはドキュメントに記載されていることではありません。 – Someone

+0

Protip: '$ timeout()'自体が約束を返します。 [遅延反パターン](http://stackoverflow.com/q/23803743/1048572)を避ける方が良い。 – Bergi

答えて

1

プランナーなしで複製するのは難しいですが、私はインスピレーションのためにコードを使って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> 
+0

これは本当に奇妙です。なぜ私のコードがうまくいかないと思いますか? – Someone

+0

プランナーを作成します。 –

関連する問題