欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

AngularJS中$http服务常用的应用及参数

程序员文章站 2023-11-14 16:13:28
前言 $http 服务:只是简单封装了浏览器原生的xmlhttprequest对象,接收一个参数,这个参数是一个对象,包含了用来生成http请求的配置内容,这个函数返回一...

前言

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

$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()函数接受两个可选的函数作为参数,表示successerror状态时的处理,也可以使用successerror回调代替: 

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"}
]

  结果:

AngularJS中$http服务常用的应用及参数

调用then()函数时返回的resp对象:

AngularJS中$http服务常用的应用及参数

总结

angularjs中$http服务常用的应用及参数到这就基本结束了,希望本文的内容能对大家学习使用angularjs有所帮助。如果有疑问可以留言交流。