AngularJS - $cancelRequest not available in $resou

2019-04-10 00:37发布

问题:

I am trying to fire abort request however, I am not getting $cancelRequest object in result of $resource. But, I am able to get $promise and $resolved objects.

Why is this happening? How can I get this $cancelRequest ?

PS: I'm using AngularJS 1.5

UPDATE: After some trial and errors I found that it was not working just because I was using AngularJS 1.5 rc 0. Now when I used AngularJS 1.5 rc 2. which is the current latest, it just worked.

回答1:

According to documentation, it is only available for Angular 1.5 :

$cancelRequest: If there is a cancellable, pending request related to the instance or collection, calling this method will abort the request.

I cannot see any mention of it on Angular 1.4...

I can only suggest you to update to 1.5 version but it is still an rc-1 version...

To enable it, you have to configure $resource, by default, it is disable :

Hash with custom settings that should extend the default $resourceProvider behavior. The supported options are:

stripTrailingSlashes – {boolean} – If true then the trailing slashes from any calculated URL will be stripped. (Defaults to true.) cancellable – {boolean} – If true, the request made by a "non-instance" call will be cancelled (if not already completed) by calling $cancelRequest() on the call's return value. This can be overwritten per action. (Defaults to false.)

Working with this code

<html ng-app="test">
<head>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.1/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.1/angular-resource.min.js"></script>

<script>
angular.module('test', ['ngResource'])
.config(function($resourceProvider) {
    $resourceProvider.defaults.cancellable = true;
})
.factory('Resource', function($resource) {
    return $resource('api/test', {}, {
        test: { cancellable : true }
    });
})
.controller('myController', function($scope, Resource) {
    Resource.query().$cancelRequest(); // ok 
    Resource.test().$cancelRequest(); // ok
});

</script>

</head>
<body ng-controller="myController">

</body>
</html>