I'm struggling with a minimal example of a $resource timing out after a couple of seconds. Probably some stupid syntactic stuff.
Ok, here's my 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) use $resource(...timeout: 3000). This gets ignored.
2) use $timeout to cancel the request after 2s. But $cancelRequest is unknown.
But unfortunately both requests to cancel my request don't work.
Can you help?
Thanks, Bernhard
Update (Working example by 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;
});
});
The $resource
factory was malformed:
/* 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);
Action methods are defined as the third argument of the factory. The second argument is for default parameters.
Usage:
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;
});
The DEMO on JSFiddle