首页 > 解决方案 > 有没有办法在新的角度应用程序中找到pendingReuests

问题描述

我正在尝试使用 selenium 自动化 Angular 应用程序。在运行 selenium 脚本之前,我想等待应用程序完全加载。我使用以下代码来执行此操作,但在应用程序更新到新的角度版本后,我无法使用此方法获取待处理的请求。我尝试了几天寻找解决方案,但找不到任何解决方案。提前致谢 :)

angular.element(document).injector().get('$http').pendingRequests.length.toString();

在此处输入图像描述

在此处输入图像描述

标签: angularjsselenium

解决方案


在最新的 Angular 中,您可以直接从内置 HTTP$ 访问 Pending Requests

或者,如果您想将其包装在此处/下面的服务外观参考中

angular.module('app', [])
// This service keeps track of pending requests
.service('pendingRequests', function() {
  var pending = [];
  this.get = function() {
    return pending;
  };
  this.add = function(request) {
    pending.push(request);
  };
  this.remove = function(request) {
    pending = _.filter(pending, function(p) {
      return p.url !== request;
    });
  };
  this.cancelAll = function() {
    angular.forEach(pending, function(p) {
      p.canceller.resolve();
    });
    pending.length = 0;
  };
})
// This service wraps $http to make sure pending requests are tracked 
.service('httpService', ['$http', '$q', 'pendingRequests', function($http, $q, pendingRequests) {
  this.get = function(url) {
    var canceller = $q.defer();
    pendingRequests.add({
      url: url,
      canceller: canceller
    });
    //Request gets cancelled if the timeout-promise is resolved
    var requestPromise = $http.get(url, { timeout: canceller.promise });
    //Once a request has failed or succeeded, remove it from the pending list
    requestPromise.finally(function() {
      pendingRequests.remove(url);
    });
    return requestPromise;
  }
}])

推荐阅读