AngularJs $http Request Service

Source: Internet
Author: User

$http

$http is a core service of angular, which facilitates browser interaction with XMLHttpRequest objects or JSONP and remote HTTP servers.

$HTTP APIs are deferred/promise APIs that are exposed based on $q services.

Quick way to use:

$http. Get

$http. Head

$http. Post

$http. Put

$http. Delete

$http. Jsonp

$http. Patch

To set the HTTP request header:

The $HTTP service will automatically create HTTP headers for all requests. This default setting can be configured completely by accessing the $httpprovider.defaults.headers configuration object. Currently contains the default configuration:

$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

Add or overwrite these default values

Add or remove properties for these configuration objects.

Global Configuration :

$httpProvider. Defaults.headers.post = {"My-header": "Value"}

single-Request configuration :

$http ({    method: "POST",    url: "url",    headers:{    "Content/  your config" )     },     // your Data "}  })

Overrides the default transformation for each request.

The following code demonstrates adding a new response transformation after the run of the default response transformation.

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

Sets the HTTP request cache.

  true/false;

Request interception

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        returnconfig; }, "Requesterror":function(rejection) {//Do something On errorIf (Canrecover (rejection)) {returnResponseornewpromise}return$q. Reject (rejection); }, "Response":function(response) {//Do something on success       returnresponse; }, "Responseerror":function(rejection) {//Do something On errorIf (Canrecover (rejection)) {returnResponseornewpromise}return$q. Reject (rejection);  }   }; }]);

dependency : $httpBackend $cacheFactory $rootScope $q $injector

Use : $http (config);

Parameters :

Method: A string that requests methods.

URL: string, request address.

params: A string or object that will be serialized using Paramserializer and as a parameter of a GET request.

Data: A string or an object that acts as the information data for the request.

headers: An object, string, or function that returns an HTTP request header that is sent to the server. If the return value of the function is null, then headers is not sent. The function accepts a configuration object as a parameter.

xsrfheadername: String that fills the HTTP request header name of the XSRF token.

xsrfcookiename: String containing the name of the XSRF token cookie.

transformrequest: An array of functions/functions. A conversion function or an array that contains a transform function. The conversion function gets the HTTP request body and the request header, and returns their conversion version (usually serialization).

transformresponse: An array of functions/functions. A conversion function or an array that contains a transform function. The conversion function gets the HTTP response body and the response header, and returns their conversion version (usually serialization).

Paramserializer: A string or a function that returns a string. A function that is used to write the string representation of a request parameter (specified as an object). If the instruction is a string, it will be interpreted as a function registered through $injector, which means that you can create your own serializer by registering the service. The default serialization is $httpparamserializer, or you can use $httpparamserializerjqlike.

Cache: Boolean, if True, a default $http cache will be cached as requested, or if there is a cache instance created with $cachefactory, it will be used for caching.

Timeout: number, milliseconds, timeout to abort the request.

withcredentials: Boolean, whether to set the XHR object for Withcredentials flag. See the credentials for more information.

responsetype: String, response header type.

return :

data: A string or an object. The response body after transformation function transformation.

Status: Value, the HTTP status code of the response.

headers: function, the getter function of the response header.

Config: object that is used to generate the requested configuration object.

statustext: String that responds with the HTTP status text.

Method :

Get (Url,[config]);

URL: Request address.

Config: Request configuration object.

Delete (Url,[donfig]);

URL: Request address.

Config: Request configuration object.

Head (Url,[config]);

URL: Request address.

Config: Request configuration object.

JSONP (Url,[config]);

URL: Request address.

Config: Request configuration object.

Post (Url,data,[config]);

URL: Request address.

Data: Request content.

Config: Request configuration object.

Put (Url,data,[config]);

URL: Request address.

Data: Request content.

Config: Request configuration object.

Patch (Url,data,[config]);

URL: Request address.

Data: Request content.

Config: Request configuration object.

Properties :

Pendingrequests

An array of configuration objects for the currently waiting request. It is mainly used for debugging purposes.

Defaults

The request header configures the default properties.

$httpParamSerializerJQLike

HTTP parameter serialization program. The serializer also sorts the parameters in alphabetical order.

Using code:

(function() {Angular.module ("Demo", []). Controller ("Testctrl", ["$http", "$httpParamSerializerJQLike", Testctrl]); functionTestctrl ($http, $httpParamSerializerJQLike) {vardata = {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);}      }); $http ({method:"POST", Data: $httpParamSerializerJQLike (data),//Form Data becomes id:1 Value:helloURL: "/url", headers: {"Content-type": "application/x-www-form-urlencoded"}, Success:function(d) {console.log (d);}    });  }; }());

Request in addition to $http, there are $resource, about the latter, and then mention, first explain the next $http, in the last example of the 2 $http request, also added headers set "Content-type": "application/ X-www-form-urlencoded ", this is because some small partners ask for no form Data, only request Payload, then when we set the Content-type value of the request header to application/ When you x-www-form-urlencoded, you can see the form data. Measurement is feasible ...

AngularJs $http Request Service

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.