AngularJS:带有 $resource 和超时的最小示例

AngularJS: Minimal example with $resource and timeout

我正在努力处理几秒钟后 $resource 超时的最小示例。可能是一些愚蠢的句法。

好的,这是我的 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) 使用 $resource(...timeout: 3000)。这会被忽略。

2) 使用$timeout 2s后取消请求。但是 $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;
    });
});

阅读文档https://docs.angularjs.org/api/ngResource/service/$resource

timeout – {number} – timeout in milliseconds. Note: In contrast to $http.config, promises are not supported in $resource, because the same value would be used for multiple requests. If you are looking for a way to cancel requests, you should use the cancellable option.

您还可以阅读这篇文章:http://corpus.hubwiz.com/2/angularjs/21666960.html

我 运行 遇到过类似的情况,我们最终意识到这必须在服务器上完成。对于我们的情况,修改服务器上的超时解决了问题。

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

动作方法被定义为工厂的第三个参数。第二个参数是默认参数。

用法:

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