使用httpInterceptor和AngularJS 1.1.5实现加载微调器

Mic*_*ker 39 angularjs

我在SO上找到了一个用于http /资源调用的加载微调器的示例:

正如您所看到的,实现工作正常(使用AngularJS 1.0.5).但是,如果您将源更改为AngularJS 1.1.5.该示例不再起作用.

我了解到$httpProvider.responseInterceptors在1.1.5 中已弃用.相反应该使用$httpProvider.interceptors

不幸的是,只是在Plunker中替换上面的字符串并没有解决问题.有没有人在AngularJS 1.1.5中使用HttpInterceptor做过这样的加载微调器?

谢谢你的帮助!

迈克尔

Mic*_*ker 111

感谢Steve的暗示,我能够实现加载器:

拦截器:

.factory('httpInterceptor', function ($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);
        }
    };
})
.config(function ($httpProvider) {
    $httpProvider.interceptors.push('httpInterceptor');
});
Run Code Online (Sandbox Code Playgroud)

指示:

.directive("loader", function ($rootScope) {
    return function ($scope, element, attrs) {
        $scope.$on("loader_show", function () {
            return element.show();
        });
        return $scope.$on("loader_hide", function () {
            return element.hide();
        });
    };
}
)
Run Code Online (Sandbox Code Playgroud)

CSS:

#loaderDiv {
   position: fixed;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
   z-index: 1100;
   background-color: white;
   opacity: .6;
}

.ajax-loader {
   position: absolute;
   left: 50%;
   top: 50%;
   margin-left: -32px; /* -1 * image width / 2 */
   margin-top: -32px; /* -1 * image height / 2 */
   display: block;
}
Run Code Online (Sandbox Code Playgroud)

HTML:

<div id="loaderDiv" loader>
    <img src="src/assets/img/ajax_loader.gif" class="ajax-loader"/>
</div>
Run Code Online (Sandbox Code Playgroud)

  • F****一个男人!我第一次复制粘贴脚本,它可以直接使用,无需修改! (3认同)

Ste*_*vis 18

"responseInterceptors"已被弃用."拦截器"取代了预览版中的许多增强功能.我不记得哪个版本.关于此的文档很少,因此您最好检查源代码.

改变的要点如下:

$httpProvider.interceptors.push(function($q, $rootScope) {
  return {
     'request': function(config) {
        // intercepts the request
     },
     'response': function(response) {
       // intercepts the response. you can examine things like status codes
     },
     'responseError': function(response) {
       // intercepts the response when the response was an error
     }
  }
});
Run Code Online (Sandbox Code Playgroud)

在角度源中,您可以在$ HttpProvider函数的"*#Interceptors"下找到文档.有一个示例用法非常类似于我上面发布的内容.