2017-05-09 5 views
0

2秒後に$リソースのタイムアウトが最小限に抑えられていると苦労しています。おそらく、いくつかの愚かな構文的なもの。

[OK]を、ここに私のjsfiddleです: http://jsfiddle.net/904dykrp/1/

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

app.controller('AppController', function($scope, $resource, $timeout) { 
    var url = "https://httpbin.org/delay/4"; // waits 4 seconds 
    var myResource = $resource(url, { 
     method: "get", 
     timeout: 3000, // 1) timeout after 3s -> gets ignored 
     isArray: true, 
     cancellable: true 
    }); 
    $timeout(function() { 
     // https://docs.angularjs.org/api/ngResource/service/$resource (at the bottom) 
     myResource.$cancelRequest(); // 2) how do I cancel? 
    }, 2000); 

    myResource.get(function(response) { 
     $scope.response = response; 
    }, function(error) { 
     // Here I want to do sth. with the cancelled request 
     $scope.error = "Request took too long, cancelled. " + error; 
    }); 
}); 

1)$リソースを(使用...タイムアウト:3000)。これは無視されます。

2)2秒後に$ timeoutを使用してリクエストをキャンセルします。しかし、$ cancelRequestは不明です。

残念ながら、私のリクエストをキャンセルする両方のリクエストは機能しません。

お手伝いできますか?

おかげで、 ベルンハルト

更新(georgeawgによって実施例):

var app = angular.module('app', ['ngResource']); 
app.controller('AppController', function($scope, $resource, $timeout) { 
    var url = "https://httpbin.org/delay/4"; // waits 4 seconds 
    var myResource = $resource(url, {}, { 
     timedGet: { 
     method: "get", 
     timeout: 3000, 
     }, 
    }); 
    var x = myResource.timedGet(); 
    x.$promise.then(function(response) { 
     console.log(response) 
     $scope.response = response; 
    }, function(error) { 
     // Here I want to do sth. with the cancelled request 
      $scope.error = "Request took too long, cancelled. " + error; 
    }); 
}); 

答えて

1

$resource工場は、不正な形式であった:

/* ERRONEOUS 
var myResource = $resource(url, { 
    method: "get", 
    timeout: 3000, // 1) timeout after 3s -> gets ignored 
    isArray: true, 
    cancellable: true 
}); 
*/ 

//BETTER 
var actions = { 
    timedGet: { 
    method: "get", 
    timeout: 3000 
    } 
};  
var myResource = $resource(url, {}, actions); 

処置方法は、工場の3番目の引数として定義されます。 2番目の引数はデフォルトのパラメータです。

使用方法:理にかなっている

var x = myResource.timedGet(); 
x.$promise.then(function(response) { 
    $scope.response = response; 
}, function(error) { 
    // Here I want to do sth. with the cancelled request 
    $scope.error = "Request took too long, cancelled. " + error; 
}); 

DEMO on JSFiddle

+0

ありがとうございました。予想どおり、私は近くにいましたが、私とAngularJSのためにしばしば起こるように、仕上げ線に達することができませんでした;-) – Bernie

0

読むのドキュメントhttps://docs.angularjs.org/api/ngResource/service/$resource

timeout – {number} - ミリ秒単位のタイムアウト。注: $http.configとは対照的に、 の複数の要求には同じ値が使用されるため、約束は$resourceでサポートされていません。 リクエストをキャンセルする方法を探している場合は、キャンセル可能なオプションを使用する必要があります。

また、あなたがこの記事を読むことができます:http://corpus.hubwiz.com/2/angularjs/21666960.html

1

私は似たような状況全体に走っていたが、我々は最終的に、これは、サーバー上で達成されなければならなかったことに気づきました。私たちの状況では、サーバーのタイムアウトを変更することで問題が解決されました。

+0

うん、。私はそれについて考えていませんでしたが、はい、良いアイデアです。 – Bernie

関連する問題