$http

get/post

$http.get('api/user', {params: {id:'5'}
}).success(function(data, status, headers, config) {
    //加载成功之后做一些事
}).error(function(data, status, headers, config) {
    //处理错误
});


var postData = {text:'long blob of text'};
//下面这一行会被当成参数附加到URL后面,所以post请求最终会变成/api/user?id=5
var config = {params: {id: '5'}};
$http.post('api/user', postData, config
).success(function(data, status, headers, config) {
    //成功之后做一些事情
}).error(function(data, status, headers, config) {
    //处理错误
});

  

设置header

默认请求头

1.Accept:appliction/json,text/pain,/

2.X-Requested-With: XMLHttpRequest

全局设置http header

$httpProvider.defaults.headers.common

$httpProvider.defaults.headers.post

$httpProvider.defaults.headers.put

$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }

临时设置header

$http(config)

var req = {
 method: 'POST',
 url: 'http://example.com',
 headers: {
   'Content-Type': undefined    //删除一个header
 },
 data: { test: 'test' }
}

$http(req).success(function(){...}).error(function(){...});

 

Request/Response格式转换

$httpProvider.defaults.transformRequest

$http.defaults.transformRequest

$http.defaults.transformResponse

$httpProvider.defaults.transformResponse

function appendTransform(defaults, transform) {

  // We can't guarantee that the default transformation is an array
  defaults = angular.isArray(defaults) ? defaults : [defaults];

  // Append the new transformation to the defaults
  return defaults.concat(transform);
}

$http({
  url: '...',
  method: 'GET',
  transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
    return doTransform(value);
  })
});//添加新的转换逻辑
//单个设置
$http.post("/url", {
      id: 1,
      name: "greengerong"
    }, {
      transformRequest: function(request) {
        return $.param(request);   //json 参数化 key1=value&key2=value2
    }
});
//全局设置
angular.module("app", [])
.config(["$httpProvider", function($httpProvider) {
      $httpProvider.defaults.transformRequest = [
        function(request) {
          return $.param(request);
        }
      ];
    }
]);

 

 

Interceptor

$httpProvider.interceptors

// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  return {
    // optional method
    'request': function(config) {
      // do something on success
      return config;
    },

    // optional method
   'requestError': function(rejection) {
      // do something on error
      if (canRecover(rejection)) {
        return responseOrNewPromise
      }
      return $q.reject(rejection);
    },



    // optional method
    'response': function(response) {
      // do something on success
      return response;
    },

    // optional method
   'responseError': function(rejection) {
      // do something on error
      if (canRecover(rejection)) {
        return responseOrNewPromise
      }
      return $q.reject(rejection);
    }
  };
});

$httpProvider.interceptors.push('myHttpInterceptor');


// alternatively, register the interceptor via an anonymous factory
$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  return {
   'request': function(config) {
       // same as above
    },

    'response': function(response) {
       // same as above
    }
  };
});

 url:http://www.webdeveasy.com/interceptors-in-angularjs-and-useful-examples/

 config

  • method – {string} – HTTP method (e.g. 'GET', 'POST', etc)
  • url – {string} – Absolute or relative URL of the resource that is being requested.
  • params – {Object.<string|Object>} – Map of strings or objects which will be serialized with theparamSerializer and appended as GET parameters.
  • data – {string|Object} – Data to be sent as the request message data.
  • headers – {Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent. Functions accept a config object as an argument.
  • xsrfHeaderName – {string} – Name of HTTP header to populate with the XSRF token.
  • xsrfCookieName – {string} – Name of cookie containing the XSRF token.
  • transformRequest – {function(data, headersGetter)|Array.<function(data, headersGetter)>} – transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version. See Overriding the Default Transformations
  • transformResponse –{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>} – transform function or an array of such functions. The transform function takes the http response body, headers and status and returns its transformed (typically deserialized) version. See Overriding the Default TransformationjqLiks
  • paramSerializer - {string|function(Object<string,string>):string} - A function used to prepare the string representation of request parameters (specified as an object). If specified as string, it is interpreted as function registered with the $injector, which means you can create your own serializer by registering it as a service. The default serializer is the $httpParamSerializer; alternatively, you can use the$httpParamSerializerJQLike
  • cache – {boolean|Cache} – If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching.
  • timeout – {number|Promise} – timeout in milliseconds, or promise that should abort the request when resolved.
  • withCredentials - {boolean} - whether to set the withCredentials flag on the XHR object. See requests with credentials for more information.
  • responseType - {string} - see XMLHttpRequest.responseType.

 

$http({
	method: string,
	url: string,
	params: object,  //[{key1: 'value1', key2: 'value2'}]   to ?key1=value&key2=value2
	data: string or object,
	headers: object,
	transformRequest: function transform(data, headersGetter) or an array of functions,
	transformResponse: function transform(data, headersGetter) or an array of functions,
	cache: boolean or Cache object,  //cache=true, 从缓存($cacheFactory)中获取response内容
	timeout: number,
	withCredentials: boolean
});

  

 

url:https://docs.angularjs.org/api/ng/service/$http

转载于:https://www.cnblogs.com/yfann/p/4689138.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值