$http服务总结

1.$http服务,利用XMLHttpRequest和jsonp发出请求,所以是异步的。

  通用形式:$http(configObject).then(function(response){},function(resason){});

  返回的是promise对象.

2.$http.defaults.headers和$httpProvider.defaults.headers可以设置默认头,在$http配置参数里面可以覆盖默认头一次。

3.在接受和发出数据时候可以转换数据

原文:If you wish to override the request/response transformations only for a single request then provide transformRequest and/ortransformResponse properties on the configuration object passed into $http.

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

4.$http请求,cache默认是关闭的。可以通过设置config参数时候,cache设置为true和$cacheFactory创建的缓存对象(针对此处请求)。也可以设置默认参数 $http.defaults.cache 和 $httpProvider.defaults.cache

5利用 $q and deferred/promise APIs.可以设置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
    }
  };
});

6.$http实现JSON Vulnerability Protection 和 CSRF保护

参考地址:https://docs.angularjs.org/api/ng/service/$http

posted on 2016-07-03 19:19  逸菜鸟  阅读(305)  评论(0)    收藏  举报