Angular,显示任何资源处于挂起状态时的加载

Dar*_*zik 5 angularjs angular-services

我已经写代码来显示装载机格,当任何资源是在之前,无论它是通过$ http.get或路由\ NG-观点得到.如果我变坏了,我不仅仅是信息......

flowHandler服务:

app.service('flowHandler', function(){
    var count = 0;
    this.init = function() { count++ };
    this.end = function() { count-- };
    this.take = function() { return count };
});
Run Code Online (Sandbox Code Playgroud)

MainCTRL附加到 <body ng-controller="MainCTRL">

app.controller("MainCTRL", function($scope, flowHandler){
    var _this = this;
    $scope.pageTitle = "MainCTRL";
    $scope.menu = [];
    $scope.loader = flowHandler.take();

    $scope.$on("$routeChangeStart", function (event, next, current) {
        flowHandler.init();
    });

    $scope.$on("$routeChangeSuccess", function (event, next, current) {
        flowHandler.end();
    });

    updateLoader = function () {
        $scope.$apply(function(){
            $scope.loader = flowHandler.take();
        });

    };

    setInterval(updateLoader, 100);

});
Run Code Online (Sandbox Code Playgroud)

和一些测试控制器通过$ http.get获取数据时:

app.controller("BodyCTRL", function($scope, $routeParams, $http, flowHandler){
    var _this = this;
    $scope.test = "git";

    flowHandler.init();
    $http.get('api/menu.php').then(function(data) {
        flowHandler.end();
        $scope.$parent.menu = data.data;

    },function(error){flowHandler.end();});
});
Run Code Online (Sandbox Code Playgroud)

现在,我已经将flowHandler服务注入任何控制器,并初始化或结束流程.

这是好主意还是它如此糟糕?

有什么建议?你是怎么做到的?

小智 3

我建议你看一下 $http 的pendingRequest 属性

https://docs.angularjs.org/api/ng/service/$http

顾名思义,它是一组仍待处理的请求。因此,您可以迭代此数组来监视特定的 URL,如果它仍处于待处理状态,则返回 true。然后你可以有一个 div 显示一个带有 ng-show 属性的加载栏来监视这个函数

我还会将此请求封装在工厂或服务中,因此我的代码如下所示:

//Service that handles requests
angular.module('myApp')
    .factory('MyService', ['$http', function($http){

  var Service = {};

  Service.requestingSomeURL = function(){
    for (var i = http.pendingRequests.length - 1; i >= 0; i--) {
      if($http.pendingRequests[i].url === ('/someURL')) return true;
    }
    return false;
  }

  return Service;
}]);


//Controller
angular.module('myApp')
    .controller('MainCtrl', ['$scope', 'MyService', function($scope, MyService){

  $scope.pendingRequests = function(){
    return MyService.requestingSomeURL();
  }
}]);
Run Code Online (Sandbox Code Playgroud)

HTML 会是这样的

<div ng-show="pendingRequests()">
  <div ng-include="'views/includes/loading.html'"></div>
</div>
Run Code Online (Sandbox Code Playgroud)