使用httpInterceptor和AngularJS实现加载

时间:2017-05-27 21:24:12

标签: javascript angularjs model-view-controller frontend

我尝试在所有网站中显示加载图标,而所有需要时间加载的组件中的请求我编写此代码但它没有工作!

这是指令和控制器

(function() {
'use strict';

angular
.module('xreview')
.directive('loading', loading);

/** @ngInject */
function loading() {
var directive = {
  restrict: 'E',
  templateUrl: 'app/components/directives/loading/loading.html',
  scope: {
  },
  controller: loadingController,
  controllerAs: 'scope',
  bindToController: true
};

return directive;

/** @ngInject */
function loadingController($rootScope , $httpInterceptor ) {
  return function ($scope, element, attrs) {
      $scope.$on("loader_show", function () {
          return element.show();
      });
      return $scope.$on("loader_hide", function () {
          return element.hide();
      });
  };
}

}

})();

这是拦截工厂

(function() {
'use strict';

angular
    .module('xreview')
    .factory('httpInterceptor', httpInterceptor);

/** @ngInject */
function httpInterceptor($q, $rootScope, $log) {

    var numLoadings = 0;

    return {
            request: function (config) {

                numLoadings++;

                // Show loader
                $rootScope.$broadcast("loader_show");
                return config || $q.when(config)

            },
            response: function (response) {

                if ((--numLoadings) === 0) {
                    // Hide loader
                    $rootScope.$broadcast("loader_hide");
                }

                return response || $q.when(response);

            },
            responseError: function (response) {

                if (!(--numLoadings)) {
                    // Hide loader
                    $rootScope.$broadcast("loader_hide");
                }

                return $q.reject(response);
            }
        };
}

})();

我在配置中注入了这个

$httpProvider.interceptors.push('httpInterceptor');

例如,这是组件的组件

的服务
vm.postAllComment = function(file){
  vm.commentig = true;
  var modal = {
    comment: vm.allCommentText
  };
  if (file.file_name != 'Post') {
    modal.post_file = file.id;
  }
  userService.one('reviews', id).post('comments', modal).then(function(result){
    vm.commentig = false;
    vm.allComments.push.apply(vm.allComments, [{
      user: result.user,
      content: result.comment,
      id: result.id
    }]);
    vm.allCommentText = '';
    vm.post.comments_count ++;
  }, function(error){
    // error post comment
    if (error.status == 403)
      userService.userUnauthenticatedHandler();
    vm.commentig = false;
  });
};

这是html

<div id="loaderDiv" loading>
  <img src="./assets/image/spinner.gif" class="ajax-loader"/>
</div>

0 个答案:

没有答案