AngularJs $http 請求服務

$httpjson

$http是Angular的一個核心服務,它有利於瀏覽器經過XMLHttpRequest 對象或者 JSONP和遠程HTTP服務器交互。數組

$HTTP API 是基於 $q服務暴露的deferred/promise APIs。promise

快捷使用方式:瀏覽器

$http.get緩存

$http.head服務器

$http.postcookie

$http.putapp

$http.deleteide

$http.jsonp函數

$http.patch

設置HTTP請求頭:

$HTTP服務將會給全部請求自動建立HTTP頭。這個默認設置能徹底的經過訪問$httpProvider.defaults.headers配置對象配置。目前包含默認配置:

  $httpProvider.defaults.headers.common
        //-- Accept:application/json,text/plain
  $httpProvider.defaults.headers.post
        //-- Content-Type:application/json
  $httpProvider.defaults.headers.put
        //-- Content-Type:application/json

添加或覆蓋這些默認值

添加或刪除這些配置對象的屬性。

全局配置

  $httpProvider.defaults.headers.post = {「my-header」:」value」}

單請求配置

  $http({
    method:」POST」,
    url:」url」,
    headers:{
    「Content-Type」:」 // your config」
    },
    data:{ data: 」 // your data」 }
  })

重寫每一個請求的默認轉換。

下面的代碼演示添加一個新的響應體轉換,在運行後的默認響應體轉換。

  Function appendTransform(defaults,transform){
    defaults:angular.isArray(defaults)?defaults:[defaults];
    return defaults.concat(transform);
  }
  $http({
    url:」url」,
    method:」GET」,
    transformResponse:appendTransform($http.defaults.transformResponse,function(){
    return doTransform(value);
    })
  })

設置http請求緩存。

  $http.defaults.cache = true/false;

請求攔截

  angular.module(「xxx」,[])
  .config([「$httpProvider」,function($httpProvider){
    $httpProvider.interceptors.push(「yourInterceptors」);
  }])
  .factory(「yourInterceptors」,[「$q」,」dependency」, function($q,dependency){
    return {
      「request」:function(config){
        // do something on success
        return config;
      },
    「requestError」:function(rejection){
       // do something on error
       If(canRecover(rejection)){
        return responseOrNewPromise
       }
       return $q.reject(rejection);
      },
    「response」:function(response){
       // do something on success
       return response;
      },
    「responseError」:function(rejection){
       // do something on error
       If(canRecover(rejection)){
         return responseOrNewPromise
       }
      return $q.reject(rejection);
      }
   };
  }]);

依賴:$httpBackend $cacheFactory $rootScope $q $injector

使用:$http(config);

參數

method:字符串,請求方法。

url:字符串,請求地址。

params:字符串或者對象,將使用paramserializer序列化而且做爲GET請求的參數。

data:字符串或者對象,做爲請求信息數據的數據。

headers:對象,字符串或者函數返回表示發送到服務器的HTTP請求頭。若是函數的返回值爲空,則headers則不發送。函數接受一個配置對象做爲參數。

xsrfHeaderName:字符串,填充XSRF令牌的HTTP請求頭名稱。

xsrfCookieName:字符串,含有XSRF令牌cookie的名字。

transformRequest:函數/函數的數組。轉換函數或者一個包含轉換函數的數組。轉換函數獲取http請求體和請求頭,而且返回他們的轉換後的數據(一般是序列化)。

transformResponse:函數/函數的數組。轉換函數或者一個包含轉換函數的數組。轉換函數獲取http響應體和響應頭,而且返回他們的轉換數據(一般是序列化)。

paramSerializer:字符串或者返回字符串的函數。用於編寫請求參數(指定爲對象)的字符串表示形式的函數。若是指令是字符串,那麼將被解釋爲經過$injector註冊的函數,這意味着你能經過註冊服務方式建立你本身的序列化程序。默認的序列化是$httpParamSerializer;或者你能夠使用$httpParamSerializerJQLike。

cache:boolean,若是爲true,一個默認的$http緩存將被做爲請求的緩存,不然若是存在一個用$cacheFactory建立的緩存實例,則將用於緩存。

timeout:數值,毫秒,超時則讓請求停止。

withCredentials:boolean,是否設置withcredentials flag的XHR對象。查看更多信息的憑據。

responseType:字符串,響應頭類型。

返回

data:字符串或對象。變換函數變換後的響應體。

status:數值,響應的http狀態碼。

headers:函數,響應頭的getter函數。

config:對象,用於生成請求的配置對象。

statusText:字符串,響應的HTTP狀態文本。

方法

get(url,[config]);

url:請求地址。

config:請求配置對象。

delete(url,[donfig]);

url:請求地址。

config:請求配置對象。

head(url,[config]);

url:請求地址。

config:請求配置對象。

jsonp(url,[config]);

url:請求地址。

config:請求配置對象。

post(url,data,[config]);

url:請求地址。

data:請求內容。

config:請求配置對象。

put(url,data,[config]);

url:請求地址。

data:請求內容。

config:請求配置對象。

patch(url,data,[config]);

url:請求地址。

data:請求內容。

config:請求配置對象。

屬性

pendingRequests

當前正在等待的請求的配置對象數組。主要是爲了用於調試目的。

defaults  

請求頭配置默認屬性。

$httpParamSerializerJQLike

Http參數序列化程序。序列化程序也將按字母順序排序的參數。

使用代碼:

(function () {
    angular.module("Demo", [])
    .controller("testCtrl",["$http", "$httpParamSerializerJQLike",testCtrl]);
    function testCtrl($http, $httpParamSerializerJQLike){
      var data = { id: 1, value: "hello" };//
      $http({
          method: "post",
          data: data,//Form Data = {"id":1,"value":"hello"}
          url: "/url",
          headers: { "Content-Type": "application/x-www-form-urlencoded" }
      }).success(function (d) { console.log(d); }).error(function(error){console.log(error);});

      $http({
          method: "post",
          data: $httpParamSerializerJQLike(data),//Form Data 變成 id:1 value:hello url: "/url",
          headers: { "Content-Type": "application/x-www-form-urlencoded" }
      }).success(function(d){ console.log(d);}).error(function(error){ console.log(error);});
    };
}());

請求除了$http,還有$resource,關於後者,後面再提,先說明下$http,在最後例子的2個$http請求的時候,還加了headers設置"Content-Type": "application/x-www-form-urlencoded",這是由於有些小夥伴提出請求沒有Form Data,只有 Request Payload,那麼當咱們設置請求頭的Content-Type值爲application/x-www-form-urlencoded時,就能看見Form Data了。實測可行...

相關文章
相關標籤/搜索