Angular - abort ajax request when using Restangular

戏子无情 提交于 2019-12-02 21:59:05

You can abort $http calls via the timeout config property, which can be a Promise, that aborts the request when resolved.

So in restangular, you can do this like

var abort = $q.defer();
Restangular.one('foos', 12345).withHttpConfig({timeout: abort.promise}).get();
abort.resolve();

To integrate it with your usecase, for example, you could have this in your service:

var abortGet;

this.getRecords = function(params) {
  ...
  if (abortGet) abortGet.resolve();
  abortGet = $q.defer();
  return Restangular
    .all('/api/records')
    .withHttpConfig({timeout: abortGet.promise})
    .post(filters);
}

This way calling getRecords always aborts the previous call if has not been resolved yet!

Hope this helps!

This is another approach if you want to abort all http requests when change the state for UI-router:

angular
    .run(function(HttpHandlerSrv) {
        HttpHandlerSrv.abortAllRequestsOn('$stateChangeSuccess');
        HttpHandlerSrv.R.setFullRequestInterceptor(function(element, operation, route, url, headers, params, httpConfig) {
            httpConfig = httpConfig || {};
            if(httpConfig.timeout === undefined) {
                httpConfig.timeout = HttpHandlerSrv.newTimeout();
            }
            return { element: element, params: params, headers: headers, httpConfig: httpConfig };
        });
    })

    .factory('HttpHandlerSrv', HttpHandlerSrv);


    /** ngInject */
    function HttpHandlerSrv($q, $rootScope, Restangular) {
        var requests = [];

        return {
            R: Restangular,
            newTimeout: newTimeout,
            abortAllRequests: abortAllRequests,
            abortAllRequestsOn: abortAllRequestsOn
        };

        function newTimeout() {
            var request = $q.defer();
            requests.push(request);
            return request.promise;
        }

        function abortAllRequests() {
            angular.forEach(requests, function(request) {
                request.resolve();
            });
            requests = [];
        }

        function abortAllRequestsOn(event) {
            $rootScope.$on(event, function(event, newUrl, oldUrl) {
                if(newUrl !== oldUrl) { abortAllRequests(); }
            });
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!