关于angularJs的拦截器的使用

拦截器,在JavaScript中就是拦截http请求.它不仅可以拦截request,还可以拦截response.

拦截request是为了在请求发送前设置一些配置,比如在header中添加一些信息.如果每个请求都要添加一些配置数据,就可以使用request拦截.拦截response是为了在获得服务器返回的数据后,ajax处理数据前先对数据做一些处理,这样就不需要在每一次ajax中处理了,减少代码量.

具体的看下面的例子:

angular.module('demo')
    //this service will let the page turn to login page when the user send post request if he is
    // not login
.factory('errorInterceptor', ['$q', '$location',
function ($q, $location) {
    return {
         requestError: function (response) {
            // some code
        }
    response: function (response) {
            // some code
        }

    responseError: function (response) {

      if (response && response.status === responseError) {
        $location.path(
'/login'); } return $q.reject(response);
      }
        request: function(req) {
        // Set the `Authorization` header for every outgoing HTTP request
        req.headers.Authorization =
          userService.getAuthorization();
        return req;
      }
}; }])

在使用之前,我们需要在config中将我们写的拦截器加入到拦截器数组中

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

 

posted @ 2016-02-04 16:49  ___delete  阅读(1138)  评论(0编辑  收藏  举报