繁体   English   中英

清除所有挂起的$ http请求并在angularjs中重新加载页面

[英]clear all pending $http requests and reload page in angularjs

我试过$ route.reload(); location.reload(真); $ window.location.reload(true);但是挂起的请求没有取消/中止,页面正在重新加载,如何硬重新加载页面意味着关闭所有挂起和重新加载页面的$ http请求。

这应该为你做的伎俩。 如果要取消请求,则需要调用abortAllPendingRequests方法。

请记住,此解决方案确实需要使用下划线。 我没有用lodash试过。

(function ()
{
  angular.module('myApp')
    .run(function ($http, $q)
    {
      $http.currentlyPendingRequests = [];

      $http.accessPendingRequests = function (pending)
      {
        if (!arguments.length) return this.currentlyPendingRequests;
        this.currentlyPendingRequests = pending;
      };

      $http.removeRequest = function (requestUrl)
      {
        this.currentlyPendingRequests = _.filter(this.currentlyPendingRequests, function (request)
        {
          return request.url !== requestUrl;
        }, this)
      };

      $http.abortAllPendingRequests = function ()
      {
        _.each(this.currentlyPendingRequests, function (request)
        {
          request.aborter.resolve();
        });

        this.currentlyPendingRequests = [];
      };

      var originalGet = $http.get;

      $http.get = function ()
      {
        // Ignore template requests
        if (arguments[0].indexOf('.html') != -1)
        {
          return originalGet.apply(this, arguments)
        };

        var aborter =  $q.defer();
        var url     = arguments[0];

        this.currentlyPendingRequests.push({url : url, aborter : aborter});
        console.log('pushing url : ' + url);

        // Include the abortion promise in the new arguments
        var newArgs        = [arguments[0], _.extend({}, arguments[1], {timeout : aborter.promise})];
        var requestPromise = originalGet.apply(this, newArgs);

        // Finally is a reserved word and is not es3 compatible, and therefore non compliant for ie8. Thus the hash
        // syntax must be used.
        requestPromise['finally'](function()
        {
          this.removeRequest(url);
        });

        return requestPromise;

      }
    });
})();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM