$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); }).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了。實測可行...