21

$http当用户单击 a 时我发出请求,<button>并且我在屏幕上禁用/隐藏/显示几个元素,直到请求返回时返回successerror

有没有办法知道$http还没有回复?我现在这样做的方式是我的控制器中有一个 var,$scope.requesting然后我在我的 HTML 页面中使用它,如下所示:

<img src="img/loader.gif" ng-show="requesting" />

所以基本上什么时候$scope.requesting是真的,显示旋转的ajaxyish loader。

如果可能的话,我想放弃$scope.requesting并使用所$http提供的任何东西,如果有的话。

登录控制器

function LoginForm($scope, $http)
{
    $scope.requesting = false;

    $scope.login = function()
    {
        $scope.requesting = true;

        $http.post('resources/request.php', data, {timeout:20000})
            .success(function(data, status, headers, config)
            {
                $scope.requesting = false;
            })
            .error(function(data, status, headers, config)
            {
                $scope.requesting = false;
            }
        );
    }
}
4

4 回答 4

33

您可以将$http.pendingRequests配置对象数组用于当前待处理的请求。可以这样使用它:

$scope.isLoading = function () {
   return $http.pendingRequests.length !== 0;
};
于 2013-03-20T17:05:10.777 回答
2

这里没有一个答案真的对我有用,我避免使用$http.pendingRequests,所以这就是我所做的

我的用例是,如果我有任何正在进行的请求在服务器上执行操作,我必须在我的视口顶部显示一个简单的“正在加载..”消息。

在里面.config,我注册了一个新的拦截器。在里面我添加了一个简单的计数器,每次请求增加 1,每次响应减少。

$httpProvider.interceptors.push([function () {
    var pendingRequestsCounter = 0;
    return {
        request: function (request) {
            pendingRequestsCounter++;
            if (pendingRequestsCounter > 0) {
                // we have some pending requests, so do something here 
            }
            return request;
        },
        response: function (response) {
            pendingRequestsCounter--;
            if (pendingRequestsCounter === 0) {
                // we have no pending requests, so do something else here 
            }
            return response;
       }
    };
}]);
于 2017-03-02T13:12:33.177 回答
1

这个jsbin 项目将@DmitryEvseev 的答案带到下一步。它可以更好地控制哪些请求可用于触发“加载...”。

这些请求{ showLoader: true }用于显示“正在加载...”面板。

HTML

  <div ng-app="app">
    <div ng-controller="spinnerController as vm">
      <div ng-if="vm.isLoading()">Loading ...</div>
    </div>
  </div>

Javascript

angular
  .module('app', [])
  .config(config)
  .factory('httpLoader', httpLoader)
  .factory('httpLoaderInterceptor', httpLoaderInterceptor)
  .controller('spinnerController', spinnerController);

function config($httpProvider) {
  //adding the default http status code handler
  $httpProvider.interceptors.push('httpLoaderInterceptor');
}

function httpLoader() {
  var pendingReqs = {};
  var factory = {
    addPendingReq: addPendingReq,
    subtractPendingReq: subtractPendingReq,
    getPendingReqs: getPendingReqs
  };
  return factory;

  function addPendingReq(url) {
    console.log('adding url', url);
    pendingReqs[url] = true;
  }

  function subtractPendingReq(url) {

    console.log('removing url', url);
    delete pendingReqs[url];
  }

  function getPendingReqs() {
    return sizeOf(pendingReqs);
  }
}

function httpLoaderInterceptor($q, httpLoader) {

  var factory = {
    request: request,
    response: response,
    responseError: responseError
  };

  return factory;

  function request(config) {
    console.log('request', config.url);
    if (config.showLoader) {
      httpLoader.addPendingReq(config.url);
    }
    return config;
  }

  function response(res) {
    console.log('response', res.config.url);
    if (res.config.showLoader) {
      httpLoader.subtractPendingReq(res.config.url);
    }
  }

  function responseError(res) {
    console.log('responseError', res.config.url);
    if (res.config.showLoader) {
      httpLoader.subtractPendingReq(res.config.url);
    }
    return $q.reject(res);
  }
}

function spinnerController($http, httpLoader) {
  var self = this;
  self.isLoading = function() {
    return httpLoader.getPendingReqs() > 0;
  };

  $http.get('http://stackoverflow.com/posts/34561385',{
    showLoader: true
  });
  $http.get('http://www.amazon.com', {
    showLoader: true
  });
  $http.get('http://www.yahoo.com',{
    showLoader: true
  });
  $http.get('http://www.stackoverflow.com',{
    showLoader: true
  });
}

function sizeOf(obj) {
  var size = 0,
    key;
  for (key in obj) {
    if (obj.hasOwnProperty(key)) {
      size++;
    }
  }
  return size;
}
于 2016-01-02T02:14:33.193 回答
0

试试这个指令: https ://github.com/afeiship/angular-isloading

CSS:

body {
  font-family: 'STHeiti', 'Microsoft YaHei', Helvetica, Arial, sans-serif;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0)
}

.loading-widget {
  width: 100px;
  height: 100px;
  margin: auto;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  position: absolute;
}

.loading-widget,
.loading-widget[data-visible] {
  display: none;
}

.loading-widget[data-visible=true] {
  display: block;
}

.loading-widget img {
  width: 100%;
  height: 100%;
}

html:

<div class="loading-widget"
     isloading
     loading="loading"
     data-visible="{{loading}}"
>
  <img src="svg/default.svg" alt="">
</div>

javascript:

  angular.module('TestApp', ['nx.widget']);

  angular.module('TestApp').
  controller('MainCtrl', function ($http, $q, $rootScope) {
    $rootScope.loading = false;
    var s1 = $http.get('http://www.baidu.com');
    var s2 = $http.get('http://www.sina.com');
    var s3 = $http.get('http://www.163.com');
    var s4 = $http.get('http://www.qq.com');
    var s5 = $http.get('http://www.hao123.com');

    //you need a VPN if you're a Chinese(Thanks to the GFW)
    var s6 = $http.get('https://www.google.com/');


    $q.all([s1, s2, s3, s4, s5, s6]).then(function (responses) {
      console.log(responses);
    })


  });

 描述:

  • 正在加载<!--1.attach the directive-->
  • 加载="加载"<!--2.write the scope.loading to the app.$rootScope-->
  • 数据可见=“{{加载}}”<!--2.read loading props for CSS-->
于 2016-05-17T09:07:16.707 回答