AngularJS的$http服務的應用

來源:互聯網
上載者:User

標籤:

$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服務的應用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.