Angularjs注入拦截器实现Loading效果

angularjs作为一个全ajax的框架,对于请求,如果页面上不做任何操作的话,在结果烦回来之前,页面是没有任何响应的,不像普通的HTTP请求,会有进度条之类。

什么是拦截器?

$httpProvider 中有一个 interceptors 数组,而所谓拦截器只是一个简单的注册到了该数组中的常规服务工厂。下面的例子告诉你怎么创建一个拦截器:

rush:js;"> module.factory('myInterceptor',['$log',function($log) { $log.debug('$log is here to show you that this is a regular factory with injection'); var myInterceptor = { .... .... .... }; return myInterceptor; }]);

然后通过它的名字添加到 $httpProvider.interceptors 数组:

rush:js;"> module.config(['$httpProvider',function($httpProvider) { $httpProvider.interceptors.push('myInterceptor'); }]);

先给大家展示下效果图:

本文通过对httpProvider注入拦截器实现loading。

HTML代码

rush:js;">

css代码

.border-radius(8px); width: 160px; height: 72px; left: 50%; margin-top: -36px; margin-left: -80px; text-align: center; img { margin-top: 12px; text-align: center; } span { display: block; } }

js代码

rush:js;"> app.config(["$routeProvider","$httpProvider",function ($routeProvider,$httpProvider) { $routeProvider.when('/',{ templateUrl: "/views/reminder/index.html",controller: "IndexController" }); $routeProvider.when('/create',{ templateUrl: "/views/reminder/item/create.html",controller: "ItemCreateController" }); $routeProvider.otherwise({redirectTo: '/'}); $httpProvider.interceptors.push('timestampMarker'); }]); //loading app.factory('timestampMarker',["$rootScope",function ($rootScope) { var timestampMarker = { request: function (config) { $rootScope.loading = true; config.requestTimestamp = new Date().getTime(); return config; },response: function (response) { // $rootScope.loading = false; response.config.responseTimestamp = new Date().getTime(); return response; } }; return timestampMarker; }]);

拦截器允许你:

通过实现 request 方法拦截请求: 该方法会在 $http 发送请求道后台之前执行,因此你可以修改配置或做其他的操作。该方法接收请求配置对象(request configuration object)作为参数,然后必须返回配置对象或者 promise 。如果返回无效的配置对象或者 promise 则会被拒绝,导致 $http 调用失败。

通过实现 response 方法拦截响应: 该方法会在 $http 接收到从后台过来的响应之后执行,因此你可以修改响应或做其他操作。该方法接收响应对象(response object)作为参数,然后必须返回响应对象或者 promise。响应对象包括了请求配置(request configuration),头(headers),状态(status)和从后台过来的数据(data)。如果返回无效的响应对象或者 promise 会被拒绝,导致 $http 调用失败。

通过实现 requestError 方法拦截请求异常: 有时候一个请求发送失败或者被拦截器拒绝了。请求异常拦截器会俘获那些被上一个请求拦截器中断的请求。它可以用来恢复请求或者有时可以用来撤销请求之前所做的配置,比如说关闭进度条,激活按钮和输入框什么之类的。

通过实现 responseError 方法拦截响应异常: 有时候我们后台调用失败了。也有可能它被一个请求拦截器拒绝了,或者被上一个响应拦截器中断了。在这种情况下,响应异常拦截器可以帮助我们恢复后台调用

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...