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