2015-09-07 152 views

回答

0

你想創建攔截器,它將建立或修改你的請求。

$ httpProvider提供程序包含一個攔截器數組。攔截器只是一個常規的服務工廠,已註冊到該陣列。這是我們如何創造一個攔截器:

  1. 創建一個攔截器的工廠。攔截器是Angular中的工廠方法,它將如下所示。

    var app = angular.module('app', []); 
    

這裏去你的攔截器

app.factory('myHttpInterceptor', function() { 

    return { 
    //Config contains all your request details 
    request: function(config) { 
     //Do you stuff here. Modify headers,pass params etc 

    return config; 
    }; 
}, 

response: function(response) { 
     //Do you stuff here with response if any and return 
     return response; 
    }, 
    responseError: function(responseError) { 
     //Handle response error here 
    } 
    }; 

}); 
  • 解決其在$ httpProvider依賴。將此行包含在您的主要模塊文件中。它可能是app.js或者通過這種方式,您可以通過發送攔截$ HTTP請求nything

    $httpProvider.interceptors.push('myHttpInterceptor'); 
    
  • 現在。希望這對你有幫助。你可以在這裏閱讀關於攔截器http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/

    +0

    想要一個攔截器,它將建立請求 –

    +0

    我給了你和上面一樣。它是一個可以構建請求的攔截器。 $ config擁有所有,您可以在發送請求之前進行修改 –