簡體   English   中英

如何通過angularjs中的攔截器發送HTTP請求?

[英]How to send the http request through interceptors in angularjs?

通常我們發送http請求為

var req={
}

and add req to the $http.get(req)..... 

但是如何從攔截器發送請求?

您想要創建將構建或修改您的請求的攔截器。

$ 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 
    }
  };

});
  1. 在$ httpProvider中解決其依賴性。 在主模塊文件中包含此行。 可能是app.js或其他

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

現在,您可以通過攔截器發送$ http請求。 希望這對您有所幫助。 您可以在http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/中了解攔截器

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM