AngularJs $http 請求服務

來源:互聯網
上載者:User

標籤:comm   編寫   cep   .config   運行   config   erro   cookie   url   

$http

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

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

快捷使用方式:

$http.get

$http.head

$http.post

$http.put

$http.delete

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

請求除了$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了。實測可行...

AngularJs $http 請求服務

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.