当前位置:AngularJS API / ng / 服务(service) / $http

ng

$http是Angular的一个核心服务,它有利于浏览器通过XMLHttpRequest 对象或者 JSONP和远程HTTP服务器交互。

$HTTP API 是基于 $q服务暴露的deferred/promise APIs。

快捷使用方式:

  • $http.get
  • $http.head
  • $http.post
  • $http.put
  • $http.delete
  • $http.jsonp
  • $http.patch

设置HTTP请求头:

$HTTP服务将会给所有请求自动创建HTTP头。这个默认设置能完全的通过访问$httpProvider.defaults.headers配置对象配置。目前包含默认配置:

  $httpProvider.defaults.headers.common
        //-- Accept:application/json,text/plain
  $httpProvider.defaults.headers.post
        //-- Content-Type:application/json
  $httpProvider.defaults.headers.put
        //-- Content-Type:application/json

添加或覆盖这些默认值

添加或删除这些配置对象的属性。

全局配置:

  $httpProvider.defaults.headers.post = {“my-header”:”value”}

单请求配置:

  $http({
    method:”POST”,
    url:”url”,
    headers:{
    “Content-Type”:” // your config”
    },
    data:{ data: ” // your data” }
  })

重写每个请求的默认转换。

下面的代码演示添加一个新的响应转换,在运行后的默认响应转换。

  Function appendTransform(defaults,transform){
    defaults:angular.isArray(defaults)?defaults:[defaults];
    return defaults.concat(transform);
  }
  $http({
    url:”url”,
    method:”GET”,
    transformResponse:appendTransform($http.defaults.transformResponse,function(){
    return doTransform(value);
    })
  })

设置http请求缓存。

  $http.defaults.cache = true/false;
 

请求拦截

  angular.module(“xxx”,[])
  .config([“$httpProvider”,function($httpProvider){
    $httpProvider.interceptors.push(“yourInterceptors”);
  }])
  .factory(“yourInterceptors”,[“$q”,”dependency”, function($q,dependency){
    return {
      “request”:function(config){
        // do something on success
        return config;
      },
    “requestError”:function(rejection){
       // do something on error
       If(canRecover(rejection)){
        return responseOrNewPromise
       }
       return $q.reject(rejection);
      },
    “response”:function(response){
       // do something on success
       return response;
      },
    “responseError”:function(rejection){
       // do something on error
       If(canRecover(rejection)){
         return responseOrNewPromise
       }
      return $q.reject(rejection);
      }
   };
  }]);

依赖

$httpBackend

$cacheFactory

$rootScope

$q

$injector


使用

$http(config);


参数

参数 类型 描述
config object
  • method:字符串,请求方法。
  • url:字符串,请求地址。
  • params:字符串或者对象,将使用paramserializer序列化并且作为GET请求的参数。
  • data:字符串或者对象,作为请求信息数据的数据。
  • headers:对象,字符串或者函数返回表示发送到服务器的HTTP请求头。如果函数的返回值为空,则headers则不发送。函数接受一个配置对象作为参数。
  • xsrfHeaderName:字符串,填充XSRF令牌的HTTP请求头名称。
  • xsrfCookieName:字符串,含有XSRF令牌cookie的名字。
  • transformRequest:函数/函数的数组。转换函数或者一个包含转换函数的数组。转换函数获取http请求体和请求头,并且返回他们的转换版(通常是序列化)。
  • transformResponse:函数/函数的数组。转换函数或者一个包含转换函数的数组。转换函数获取http响应体和响应头,并且返回他们的转换版(通常是序列化)。
  • paramSerializer:字符串或者返回字符串的函数。用于编写请求参数(指定为对象)的字符串表示形式的函数。如果指令是字符串,那么将被解释为通过$injector注册的函数,这意味着你能通过注册服务方式创建你自己的序列化程序。默认的序列化是$httpParamSerializer;或者你可以使用$httpParamSerializerJQLike。
  • cache:boolean,如果为true,一个默认的$http缓存将被作为请求的缓存,否则如果存在一个用$cacheFactory创建的缓存实例,则将用于缓存。
  • timeout:数值,毫秒,超时则让请求中止。
  • withCredentials:boolean,是否设置withcredentials flag的XHR对象。查看更多信息的凭据。
  • responseType:字符串,响应头类型。

返回

  • data:字符串或对象。变换函数变换后的响应体。
  • status:数值,响应的http状态码。
  • headers:函数,响应头的getter函数。
  • config:对象,用于生成请求的配置对象。
  • statusText:字符串,响应的HTTP状态文本。

方法

get(url,[config]);

参数 类型 描述
url string 请求地址。
config object 请求配置对象。

delete(url,[donfig]);

参数 类型 描述
url string 请求地址。
config object 请求配置对象。

head(url,[config]);

参数 类型 描述
url string 请求地址。
config object 请求配置对象。

jsonp(url,[config]);

参数 类型 描述
url string 请求地址。
config object 请求配置对象。

post(url,data,[config]);

参数 类型 描述
url string 请求地址。
data * 请求内容。
config object 请求配置对象。

put(url,data,[config]);

参数 类型 描述
url string 请求地址。
data * 请求内容。
config object 请求配置对象。

patch(url,data,[config]);

参数 类型 描述
url string 请求地址。
data * 请求内容。
config object 请求配置对象。

属性

pendingRequests

当前正在等待的请求的配置对象数组。主要是为了用于调试目的。

defaults

请求头配置默认属性。

$httpParamSerializerJQLike

Http参数序列化程序。序列化程序也将按字母顺序排序的参数。


示例

<div ng-controller="FetchController">
  <select ng-model="method" aria-label="Request method">
    <option>GET</option>
    <option>JSONP</option>
  </select>
  <input type="text" ng-model="url" size="80" aria-label="URL" />
  <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  <button id="samplejsonpbtn"
    ng-click="updateModel('JSONP',
                  'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
    Sample JSONP
  </button>
  <button id="invalidjsonpbtn"
    ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
      Invalid JSONP
    </button>
  <pre>http status code: {{status}}</pre>
  <pre>http response data: {{data}}</pre>
</div>
angular.module('httpExample', [])
.controller('FetchController', ['$scope', '$http', '$templateCache',
  function($scope, $http, $templateCache) {
    $scope.method = 'GET';
    $scope.url = 'http-hello.html';

    $scope.fetch = function() {
      $scope.code = null;
      $scope.response = null;

      $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
        then(function(response) {
          $scope.status = response.status;
          $scope.data = response.data;
        }, function(response) {
          $scope.data = response.data || 'Request failed';
          $scope.status = response.status;
      });
    };

    $scope.updateModel = function(method, url) {
      $scope.method = method;
      $scope.url = url;
    };
  }]);
Hello, $http!
 var status = element(by.binding('status'));
  var data = element(by.binding('data'));
  var fetchBtn = element(by.id('fetchbtn'));
  var sampleGetBtn = element(by.id('samplegetbtn'));
  var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));

  it('should make an xhr GET request', function() {
    sampleGetBtn.click();
    fetchBtn.click();
    expect(status.getText()).toMatch('200');
    expect(data.getText()).toMatch(/Hello, \$http!/);
  });

// Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
// it('should make a JSONP request to angularjs.org', function() {
//   var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
//   sampleJsonpBtn.click();
//   fetchBtn.click();
//   expect(status.getText()).toMatch('200');
//   expect(data.getText()).toMatch(/Super Hero!/);
// });

  it('should make JSONP request to invalid URL and invoke the error handler',
      function() {
    invalidJsonpBtn.click();
    fetchBtn.click();
    expect(status.getText()).toMatch('0');
    expect(data.getText()).toMatch('Request failed');
  });