前言
$http 服務(wù):只是簡單封裝了瀏覽器原生的XMLHttpRequest對象,接收一個參數(shù),這個參數(shù)是一個對象,包含了用來生成HTTP請求的配置內(nèi)容,這個函數(shù)返回一個promise對象,具有success和error方法。
$http服務(wù)的使用場景:
var promise = $http({method:"post", // 可以是get,post,put, delete,head,jsonp;常使用的是get,posturl:"./data.json", //請求路徑params:{'name':'lisa'}, //傳遞參數(shù),字符串map或?qū)ο?,轉(zhuǎn)化成?name=lisa形式跟在請求路徑后面data:blob, //通常在發(fā)送post請求時使用,發(fā)送二進(jìn)制數(shù)據(jù),用blob對象。}).success(function(data){//響應(yīng)成功操作}).error(function(data){//響應(yīng)失敗(響應(yīng)以錯誤狀態(tài)返回)操作})then()函數(shù):可以使用then()函數(shù)來處理$http服務(wù)的回調(diào),then()函數(shù)接受兩個可選的函數(shù)作為參數(shù),表示success或error狀態(tài)時的處理,也可以使用success和error回調(diào)代替:
then(successFn, errFn, notifyFn) ,無論promise成功還是失敗了,當(dāng)結(jié)果可用之后, then都會立刻異步調(diào)用successFn或者errFn。這個方法始終用一個參數(shù)來調(diào)用回調(diào)函數(shù):結(jié)果,或者是拒絕的理由。
在promise被執(zhí)行或者拒絕之前, notifyFn回調(diào)可能會被調(diào)用0到多次,以提供過程狀態(tài)的提示
promise.then(function(resp){//響應(yīng)成功時調(diào)用,resp是一個響應(yīng)對象}, function(resp) {// 響應(yīng)失敗時調(diào)用,resp帶有錯誤信息});then()函數(shù)接收的resp(響應(yīng)對象)包含5個屬性:
1. data(字符串或?qū)ο螅?/strong>響應(yīng)體
2. status:相應(yīng)http的狀態(tài)碼,如200
3. headers(函數(shù)):頭信息的getter函數(shù),可以接受一個參數(shù),用來獲取對應(yīng)名字的值
4. config(對象):生成原始請求的完整設(shè)置對象
5. statusText:相應(yīng)的http狀態(tài)文本,如"ok"
或者使用success/error方法,使用
//成功處理promise.success(function(data, status, headers, config){// 處理成功的響應(yīng)});// 錯誤處理promise.error(function(data, status, headers, config){// 處理非成功的響應(yīng)});使用實例:
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"}]結(jié)果:

調(diào)用then()函數(shù)時返回的resp對象:

總結(jié)
AngularJS中$http服務(wù)常用的應(yīng)用及參數(shù)到這就基本結(jié)束了,希望本文的內(nèi)容能對大家學(xué)習(xí)使用AngularJS有所幫助。如果有疑問可以留言交流。
新聞熱點(diǎn)
疑難解答