zoukankan      html  css  js  c++  java
  • $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

  • 相关阅读:
    Linux基础之计算机硬件
    python中 __cmp__
    python中 __str__和__repr__
    python的构造函数传入任意数量的参数
    python中的偏函数
    javascript正则表达式
    js实现复选框的全选、全部选和反选
    js中的函数对象
    js中的作用域
    js中的arguments
  • 原文地址:https://www.cnblogs.com/yfann/p/4689138.html
Copyright © 2011-2022 走看看