AngularJs $http 请求服务

来源:互联网 发布:mac玩魔兽世界卡吗 编辑:程序博客网 时间:2024/04/30 02:09

$http

$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);

参数

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:请求地址。

config:请求配置对象。

delete(url,[donfig]);

url:请求地址。

config:请求配置对象。

head(url,[config]);

url:请求地址。

config:请求配置对象。

jsonp(url,[config]);

url:请求地址。

config:请求配置对象。

post(url,data,[config]);

url:请求地址。

data:请求内容。

config:请求配置对象。

put(url,data,[config]);

url:请求地址。

data:请求内容。

config:请求配置对象。

patch(url,data,[config]);

url:请求地址。

data:请求内容。

config:请求配置对象。

属性

pendingRequests

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

defaults  

请求头配置默认属性。

$httpParamSerializerJQLike

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

使用代码:

复制代码
(function () {    angular.module("Demo", [])    .controller("testCtrl",["$http", "$httpParamSerializerJQLike",testCtrl]);    function testCtrl($http, $httpParamSerializerJQLike){      var data = { id: 1, value: "hello" };//      $http({          method: "post",          data: data,//Form Data = {"id":1,"value":"hello"}          url: "/url",          headers: { "Content-Type": "application/x-www-form-urlencoded" }      }).success(function (d) { console.log(d); }).error(function(error){console.log(error);});      $http({          method: "post",          data: $httpParamSerializerJQLike(data),//Form Data 变成 id:1 value:hello url: "/url",          headers: { "Content-Type": "application/x-www-form-urlencoded" }      }).success(function(d){ console.log(d);}).error(function(error){ console.log(error);});    };}());
复制代码

请求除了$http,还有$resource,关于后者,后面再提,先说明下$http,在最后例子的2个$http请求的时候,还加了headers设置"Content-Type": "application/x-www-form-urlencoded",这是因为有些小伙伴提出请求没有Form Data,只有 Request Payload,那么当我们设置请求头的Content-Type值为application/x-www-form-urlencoded时,就能看见Form Data了。实测可行...