AngularJS的$http服务的应用

$http有很多参数和调用方法,本文只记录比较常用的应用及参数。

$http 服务:只是简单封装了浏览器原生的XMLHttpRequest对象,接收一个参数,这个参数是一个对象,包含了用来生成HTTP请求的配置内容,这个函数返回一个promise对象,具有success和error方法。

$http服务的使用场景:

var promise = $http({
method:"post",          // 可以是get,post,put, delete,head,jsonp;常使用的是get,post
url:"./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回调代替: 

then(successFn, errFn, notifyFn),无论promise成功还是失败了,当结果可用之后, then都会立刻异步调用successFn或者

errFn。这个方法始终用一个参数来调用回调函数:结果,或者是拒绝的理由。
在promise被执行或者拒绝之前, notifyFn回调可能会被调用0到多次,以提供过程状态的
提示

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对象:

 

原文地址:https://www.cnblogs.com/whh412/p/5644458.html