使用 promise 对象中止 ngResource

Aborting ngResource using a promise object

我最近了解到可以通过以毫秒为单位指定超时或传递延迟对象来中止 ngResource 请求。

第二个解决方案似乎对我不起作用,我也不知道我做错了什么。我创建了一个 fiddle 来演示问题 http://jsfiddle.net/HB7LU/10977/

var myApp = angular.module('myApp',['ngResource']);

myApp.factory('myResource', function($resource) {
    return {
      getResource: function (aborter) {
        var resource = $resource(
            'http://api.openweathermap.org/data/2.5/weather?q=London,uk', {}, {
          query: {
            isArray: false,
            timeout: aborter.promise
          }
        });

        return resource;
      }
    };
});

myApp.controller('MyCtrl', function($scope, $q, $log, $timeout, myResource) {
    var aborter = $q.defer();
    setTimeout(function() {
       $log.info('Aborting...');
       aborter.resolve();
    }, 10);
    myResource.getResource(aborter).query().$promise.then(function(data) {
        $scope.data = data;
    });
});

我想避免同时发送多个请求(我想通过调用 aborter.resolve().

取消之前的请求

我一直在关注这个解决方案 你能告诉我为什么它不起作用吗?

尝试使用 $timeout,而不是 setTimeout,因为这样可以确保您的决心被 angular $digest 周期捕获。

myApp.controller('MyCtrl', function($scope, $q, $log, $timeout, myResource) {
    var aborter = $q.defer();
    $timeout(function() {
       $log.info('Aborting...');
       aborter.resolve();
    }, 10);
    myResource.getResource(aborter).query().$promise.then(function(data) {
        $scope.data = data;
    });
});

这似乎是 Angular 1.3 的未解决问题:github.com/angular/angular.js/issues/9332 如果你回到 1.2.28,你的 jsfiddle 就可以工作了。

尝试更改这行 ngResource 源代码:

httpConfig[key] = copy(value);

httpConfig[key] = key !== 'timeout' ? copy(value) : value;

问题是复制的承诺