Angular統一攔截器(httpInterceptor)

angular中提供了這樣的攔截器接口$httpProvider.interceptors,只要按格式要求定一個httpInterceptor(這個名字是自定義的,可是其擁有的屬性必需要嚴格按照必定格式)的factory。可能像下面這個樣子:javascript

var myApp = angular.module("myApp", []); //首先定一個app 

//定義http攔截器httpInterceptor,這個factory返回的對象能夠擁有responseError,response,request,requestError這些屬性,分別對應攔截的處理。
myApp.factory('httpInterceptor', [ '$q',function($q) { 
    var httpInterceptor = { 
      'responseError' : function(response) { //響應錯誤攔截
        //這裏能夠對不一樣的響應錯誤進行處理,好比根據返回狀態碼進行特殊處理
        switch(response。status) {
            case 404:
                alert("找不到頁面");
                break;
            case 403:
                alert("沒有權限");
                break;
            defalut:
                ....
        }
        return $q.reject(response); 
      }, 
      'response' : function(response) {     //響應攔截
        //這裏能夠對全部的響應的進行處理
        return response; 
      }, 
      'request' : function(config) {        //請求攔截
        //這裏能夠對全部的請求進行處理
        return config; 
      }, 
      'requestError' : function(config){    //請求錯誤攔截
        //這裏能夠對全部的請求錯誤進行處理
        return $q.reject(config); 
      } 
    } 
  return httpInterceptor; 
}
//定義了httpInterceptor以後,須要手動添加到$httpProvider.interceptors中去才能讓攔截器生效
myApp.config([ '$httpProvider', function($httpProvider) { 
  $httpProvider.interceptors.push('httpInterceptor'); //添加攔截器
} ]);

使用仍是比較簡單的,可是* 須要注意是攔截的請求只能是經過angular中的$http發送的請求和響應才能被httpInterceptor攔截,ajax發送或其餘方式的請求不可以被httpInterceptor攔截! *,因此當使用其餘方式發送請求時,在httpInterceptor中不能被攔截的時候要清楚這一點。若是使用ajax發送請求,就須要在ajax中的successerror中單獨進行處理,可能以下:java

$.ajax({
    url: '/test',
    dataType: 'json',
    statusCode: {  //對響應狀態碼進行攔截
        404: function(){
            alert("找不到頁面");
        },
        403: function(){
            alert("沒有權限");
        }
        ......
    },
    success: function(){
        //對成功響應進行處理
    },
    error: function(){
        //對響應錯誤進行處理
    }
});

上面angular攔截器中有寫到$q$qangular中的提供promise服務的模塊,能夠去網上搜一下,有不少參考資料,這裏不進行詳解了。記住幾個經常使用的接口就好了,deferresolvereject ,notify參考官方文檔angularjs

相關文章
相關標籤/搜索