$http服務(wù)的使用場(chǎng)景:
var promise = $http({
method: "post",//發(fā)送請(qǐng)求的方式,get,post,put,delete,head,jsop;常用get post
url: "data.json", //請(qǐng)求的地址
params: {"name": "lisa"},//傳遞參數(shù),轉(zhuǎn)換name=lisa的形式跟在請(qǐng)求路徑的后面
data:blod//通常是在發(fā)送post請(qǐng)求時(shí)使用,
}).success(function(data) {
console.log("響應(yīng)成功");
}).error(function() {
console.log("響應(yīng)失敗");
})
then()函數(shù):可以用來(lái)處理$http服務(wù)的回調(diào),then()函數(shù)接受兩個(gè)可選的函數(shù)作為參數(shù),表示sucees或者error狀態(tài)的處理,也可以使用success和error回調(diào)代替;then(successFn,errFn,nontifyFn),無(wú)論promise成功還是失敗了,then都會(huì)立刻異步調(diào)用successFn或者errFn.這個(gè)方法始終用一個(gè)參數(shù)來(lái)調(diào)用回調(diào)函數(shù),
promise.then(function(response) {
//響應(yīng)成功時(shí)調(diào)用,response是一個(gè)響應(yīng)對(duì)象;
},function(response) {
//響應(yīng)失敗時(shí)調(diào)用,resp帶有錯(cuò)誤信息
});
then()函數(shù)接受response響應(yīng)對(duì)象包含5個(gè)屬性:
- data: 響應(yīng)的數(shù)據(jù);
- status:相應(yīng)http的狀態(tài)碼,如200;
- headers:頭信息的getter函數(shù),可以接受一個(gè)參數(shù),用來(lái)獲取對(duì)應(yīng)名字的值;
- config(對(duì)象):生成原始請(qǐng)求的完整設(shè)置對(duì)象;
- 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()方法來(lái)處理$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);
})
});