我正在尝试触发中止请求,但是我没有收到 $cancelRequest
$resource
结果中的对象.但是,我可以得到 $promise
和 $resolved
对象。
为什么会这样?我怎样才能得到这个 $cancelRequest
?
PS:我使用的是 AngularJS 1.5
更新 :经过一些试验和错误后,我发现它不能正常工作,因为我使用的是 AngularJS 1.5 rc 0。现在当我使用 AngularJS 1.5 rc 2. 这是当前的最新版本时,它可以正常工作。
最佳答案
根据文档,它仅适用于 Angular 1.5 :
$cancelRequest: If there is a cancellable, pending request related to the instance or collection, calling this method will abort the request.
我在 Angular 1.4 上看不到任何提及...
我只能建议你更新到 1.5 版本,但它仍然是 rc-1 版本......
要启用它,您必须配置 $resource,默认情况下,它是 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.)
使用此代码
<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>
关于AngularJS - $cancelRequest 在 $resource 中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35066781/