標籤:
$http有很多參數和調用方法,本文只記錄比較常用的應用及參數。
$http 服務:只是簡單封裝了瀏覽器原生的XMLHttpRequest對象,接收一個參數,這個參數是一個對象,包含了用來產生HTTP請求的配置內容,這個函數返回一個promise對象,具有success和error方法。
$http服務的使用情境:
var promise = $http({method:"post", // 可以是get,post,put, delete,head,jsonp;常使用的是get,posturl:"./data.json", //請求路徑params:{‘name‘:‘lisa‘}, //傳遞參數,字串map或對象,轉化成?name=lisa形式跟在請求路徑後面data:blob, //通常在發送post請求時使用,發送位元據,用blob對象。}).success(function(data){//響應成功操作}).error(function(data){//響應失敗(響應以錯誤狀態返回)操作})
then()函數:可以使用then()函數來處理$http服務的回調,then()函數接受兩個可選的函數作為參數,表示success或error狀態時的處理,也可以使用success和error回調代替:
promise.then(function(resp){//響應成功時調用,resp是一個響應對象}, function(resp) {// 響應失敗時調用,resp帶有錯誤資訊});
then()函數接收的resp(響應對象)包含5個屬性:
1. data(字串或對象):響應體
2. status:相應http的狀態代碼,如200
3. headers(函數):頭資訊的getter函數,可以接受一個參數,用來擷取對應名字的值
4. config(對象):產生原始請求的完整設定對象
5. statusText:相應的http狀態文本,如"ok"
或者使用success/error方法,使用
//成功處理
promise.success(function(data, status, headers, config){// 處理成功的響應});// 錯誤處理promise.error(function(data, status, headers, config){// 處理非成功的響應});
使用執行個體:
<!--index.html-->
<!doctype html><html lang="en"><head> <meta charset="UTF-8"> <title>$http request test </title> <script src="../js/angular.js"></script> <script src="app.js"></script></head><body><div data-ng-app="myApp" data-ng-controller="myAppController" data-ng-init="loadData()"> <table> <thead> <tr> <th>名稱</th> <th>屬性</th> </tr> </thead> <tbody> <tr data-ng-repeat="data in myData"> <td>{{data.name}}</td> <td>{{data.attr}}</td> </tr> </tbody> </table></div></body></html>
//app.js
var myHttpApp = angular.module("myApp",[]);myHttpApp.controller("myAppController",function($q,$http,$scope){ var deffer = $q.defer(); var data = new Blob([{ "name":"zhangsan" }]) $scope.loadData = function(){ var promise = $http({ method:"post", url:"./data.json", cache: true }).success(function(data){ deffer.resolve(data); }).error(function(data){ deffer.reject(data); }) promise.then(function(data){ $scope.myData = data.data; }) /*promise.success(function(data){ $scope.myData = data; })*/ }})
//data.json[ {"name":"zhangsan","attr":"China"}, {"name":"lisa","attr":"USA"}, {"name":"Bob","attr":"UK"}, {"name":"Jecy","attr":"Jepan"}]
結果:
調用then()函數時返回的resp對象:
AngularJS的$http服務的應用