Aborting ngResource using a promise object

拟墨画扇 提交于 2019-12-19 21:50:40

问题


I've recently learned that ngResource request can be aborted either by specifying a timeout in ms or passing a deferred object.

The second solution does not seem to work for me, and I have no idea what I'm doing wrong. I've created a fiddle to demonstrate the problem 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;
    });
});

I want to avoid sending multiple request at the time (I want to cancel the previous by calling aborter.resolve().

I was following this solution Angular $http : setting a promise on the 'timeout' config Could you please advice me why it does not work?


回答1:


It looks like it's an open issue with Angular 1.3: github.com/angular/angular.js/issues/9332 You're jsfiddle works if you drop back to 1.2.28.




回答2:


Try using $timeout, instead of setTimeout, since that will take care of making sure your resolve is captured by angular $digest cycle.

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;
    });
});



回答3:


try to change this line of ngResource source code:

httpConfig[key] = copy(value);

in

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

the problem is the copied promise



来源:https://stackoverflow.com/questions/28497318/aborting-ngresource-using-a-promise-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!