使用$http发送请求的时候显示loading

来源:互联网 发布:python自动化测试虫师 编辑:程序博客网 时间:2024/06/06 18:32

由于是单页应用, 所以在index.html中必有这样一行:

<div ui-view=""></div>

在这一行下面添加以下代码:

<div id="loading" ng-show="showLoading">    <div class="spinner">        <img src="images/loading.gif" style="z-index: 999">    </div></div>

CSS:

#loading {  position: fixed; /* Sit on top of the page content */  display: block; /* Hidden by default */  width: 100%; /* Full width (cover the whole page) */  height: 100%; /* Full height (cover the whole page) */  top: 0;  left: 0;  right: 0;  bottom: 0;  background-color: rgba(0, 0, 0, 0.5); /* Black background with opacity */  z-index: 2000; /* Specify a stack order in case you're using a different order for other elements */  cursor: pointer; /* Add a pointer on hover */}.spinner {  margin: 0 auto;  position: relative;  top: 35%;  width: 1px;  z-index: 2147483647;}

不要忘了给body添加属性:

<body ng-class="{true: 'modal-open', false: ''}[showLoading]">

若不启动蒙版, 显示loading 的时候依然能够在页面上操作, 因为用了bootstrap, 所以添加modal-open就能够开启蒙版了.

JS:

angular.module('listener', [])    .run(["$rootScope", '$injector',        function ($rootScope, $injector) {            $rootScope.showLoading = false;            $rootScope.$on('loading:show', function () {                $rootScope.showLoading = true;            });            $rootScope.$on('loading:hide', function () {                $rootScope.showLoading = false;            });            $rootScope.$on('request:404', function () {                swal({                    title: "请求出错!",                    type: "error",                    timer: 1000,                    showConfirmButton: false,                    allowOutsideClick:true                });            });              }]    );angular.module('interceptor', [])    .config(['$httpProvider',        function ($httpProvider) {            var requestInterceptor = ['$q', '$injector', '$rootScope',                function ($q, $injector, $rootScope) {                    return {                        request: function (config) {                            $rootScope.$broadcast('loading:show');                            return config || $q.when(config);                        },                        response: function (response) {                            $rootScope.$broadcast('loading:hide');                            return response;                        },                        responseError: function (response) {                            $rootScope.$broadcast('loading:hide');                            return $q.reject(response);                        },                        requestError: function (response) {                            $rootScope.$broadcast('loading:hide');                            return response;                        }                    };                }];            $httpProvider.interceptors.push(requestInterceptor);        }]);

另附生成loading图片的地址:
https://loading.io/

原创粉丝点击