您的位置:首页 > Web前端 > AngularJS

Angularjs注入拦截器实现Loading效果

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

什么是拦截器?

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

<!-- lang: 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 数组:

<!-- lang: js -->
module.config(['$httpProvider', function($httpProvider) {
 $httpProvider.interceptors.push('myInterceptor');
}]);


先给大家展示下效果图:



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

html代码

<div class="loading-modal modal" ng-if="loading">
 <div class="loading">
  <img src="<?=$this->module->getAssetsUrl()?>/img/loading.gif" alt=""/><span ng-bind="loading_text"></span>
 </div>
</div>


css代码

.modal {
 position: fixed;
 width: 100%;
 height: 100%;
 left: 0;
 top: 0;
 z-index: 99;
 background: rgba(0, 0, 0, 0.3);
 overflow: hidden;
}
.loading {
 position: absolute;
 top: 50%;
 background: white;
 #solution> .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代码

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 方法拦截响应异常: 有时候我们后台调用失败了。也有可能它被一个请求拦截器拒绝了,或者被上一个响应拦截器中断了。在这种情况下,响应异常拦截器可以帮助我们恢复后台调用。

您可能感兴趣的文章:

浅析AngularJs HTTP响应拦截器
快速学习AngularJs HTTP响应拦截器
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: