AngularJS:$ resource和timeout的最小示例

时间:2017-05-09 17:53:44

标签: angularjs angularjs-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;
    });
});

3 个答案:

答案 0 :(得分:2)

$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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

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

  

timeout – {number} - 超时(以毫秒为单位)。注意:与之相反   $http.config$resource不支持承诺,因为   相同的值将用于多个请求。如果您正在寻找   一种取消请求的方法,你应该使用可取消的选项。

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