$http服務(wù)的使用場景:
var promise = $http({
method: "post",//發(fā)送請求的方式拦键,get,post,put,delete,head,jsop;常用get post
url: "data.json", //請求的地址
params: {"name": "lisa"},//傳遞參數(shù)虏肾,轉(zhuǎn)換name=lisa的形式跟在請求路徑的后面
data:blod//通常是在發(fā)送post請求時使用,
}).success(function(data) {
console.log("響應(yīng)成功");
}).error(function() {
console.log("響應(yīng)失敗");
})
then()函數(shù):可以用來處理$http服務(wù)的回調(diào),then()函數(shù)接受兩個可選的函數(shù)作為參數(shù)倔既,表示sucees或者error狀態(tài)的處理,也可以使用success和error回調(diào)代替鹏氧;then(successFn,errFn,nontifyFn),無論promise成功還是失敗了渤涌,then都會立刻異步調(diào)用successFn或者errFn.這個方法始終用一個參數(shù)來調(diào)用回調(diào)函數(shù),
promise.then(function(response) {
//響應(yīng)成功時調(diào)用把还,response是一個響應(yīng)對象实蓬;
},function(response) {
//響應(yīng)失敗時調(diào)用,resp帶有錯誤信息
});
then()函數(shù)接受response響應(yīng)對象包含5個屬性:
- data: 響應(yīng)的數(shù)據(jù)吊履;
- status:相應(yīng)http的狀態(tài)碼安皱,如200;
- headers:頭信息的getter函數(shù)率翅,可以接受一個參數(shù)练俐,用來獲取對應(yīng)名字的值;
- config(對象):生成原始請求的完整設(shè)置對象冕臭;
- statusText:響應(yīng)的http狀態(tài)文本腺晾,如OK;
或者直接使用success/error方法:
prmoise.success(function(data, status, headers, config) {
// 處理成功的響應(yīng)
});
prmoise.error(function(data, status, headers, config) {
//處理非成功的響應(yīng)
})
示例:
//html
<body ng-app="myApp" ng-controller="myCtrl" ng-init="loadData()">
<table>
<thead>
<tr>
<th>名稱</th>
<th>屬性</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="data in myData">
<td>{{data.name}}</td>
<td>{{data.attr}}</td>
</tr>
</tbody>
</table>
</body>
success和error的方法
var app = angular.module("myApp",[]);
app.controller("myCtrl", function($scope, $http) {
$http({
method: "get",
url: "data.json"
}).success(function(data, herders, status, config) {
console.log(data);
$scope.myData = data;
}).error(function(data, herders, status, config) {
console.log(data)
})
})
then()方法來處理$http服務(wù)的回調(diào);
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http) {
$http.get("data.json").then(function(response) {
$scope.myData = response.data//
},function(response) {
console.log(response.statusText);
})
});