Angular $http Services

Source: Internet
Author: User

$http Services

The angular built-in $http service simply encapsulates the native XMLHttpRequest object of the browser and can communicate directly with the outside.

The $http service can accept only one parameter, which is an object that mainly contains the configuration content of some HTTP requests. Such as:

 var  req = {method:  ' POST '  ' Content-typ E ': ' application/x-www-form-urlencoded '  ' Test ' 

You can see that the $http () method returns a Promise object, and we can also use the then callback when the response is returned. However, using the then callback will give you a special parameter that represents the success or failure information for the corresponding object, and you can accept two optional functions as parameters. Such as:

$http (req) then (function(resp    ) {//resp is a response object },function  (resp) {    // RESP} with error message);

the difference between the T hen () method callback and the success (), error () callback is that then () receives the complete object, and success () and error () deconstruct the response.

The $http method in Ng

$http
$http. Get
$http. Head
$http. Post
$http. Put
$http. Delete
$http. Jsonp
$http. Patch

usage of $http ()  
Some parameters and descriptions

Parameters Description
Method Request method
Url Request Address
Params A string or object that will be serialized using Paramserializer and as a parameter to the GET request.
Data A string or object that acts as data for the requested information data.
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.
Xsrfheadername Populate the HTTP request header name for the XSRF token
Xsrfcookiename The name of the cookie containing the XSRF token
Transformrequest An array of functions/functions. A conversion function or an array that contains a transform function. The transform function gets the HTTP request body and the request header, and returns their converted data (usually serialized).
Transformresponse An array of functions/functions. A conversion function or an array that contains a transform function. The transform function gets the HTTP response body and the response header, and returns their transformation data (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 If true, a default cache will be cached as requested, or if there is a cache instance created with Cachefactory, it will be used for caching.
Timeout Value, milliseconds, timeout to abort the request.
Withcredentials Boolean, whether to set the XHR object for Withcredentials flag. See the credentials for more information.
Responsetype Response header Type

The parameters returned:

Parameters Description
Data A string or an object. The response body after transformation function transformation.
Status 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 A string that responds to the HTTP status text.

$http.get (Url,[config]) $http. Delete (Url,[donfig]) $http. Head (Url,[config]) $http . JSONP (Url,[config])

The parameters in these four methods are:
URL: Request address.
Config: Request configuration object.

$http. Post (Url,data,[config]) $http. Put (Url,data,[config]) $http. Patch (url,data,[ Config])

More than four of these three methods have more than one parameter data, which represents the requested content.
The above is the content of $http service.

$http Test

Angular $http service is relatively simple, here again to introduce the $http service test.
To give a simple example:

var app = Angular.module (' Application ', []); App.controller (function($scope, $http) {    $http. Get (' Users/users.json '). Success (function(data) {        = data;    });     = ' Hello world! ' ;});

We mainly use angular with the $httpbackend set pseudo-background, when trying, we do not need to send a real HTTP request to obtain data. If only the logic of the service can be tested, when the request is sent, we intercept the request and return a pre-defined good data.

Describe (' Mainctrl ',function() {    //We will use this scope in our tests.    varscope, $httpBackend; //simulate our application module and inject our own dependenciesBeforeeach (Angular.mock.module (' Application '))); //simulates a controller and contains $rootScope and $controllerBeforeeach (Angular.mock.inject (function($rootScope, $controller, _$httpbackend_) {//set $httpbackend flushing $http request$httpBackend =_$httpbackend_; $httpBackend. When (' GET ', ' Users/users.json '). Respond ([{ID:1, Name:' Bob '}, {ID:2, Name:' Jane '        }]); //Create an empty scopeScope = $rootScope. $New(); //declares a controller and injects an empty scope that has been created$controller (' Mainctrl ', {$scope: scope});    })); //The test starts here .It (' should has variable text = "Hello world!" ',function() {expect (scope.text). ToBe (' Hello world! ');    }); It (' Should fetch list of users ',function() {$httpBackend. Flush (); Expect (scope.users.length). ToBe (2); Expect (scope.users[0].name). ToBe (' Bob ')); //output results for easy viewing         for(vari=0;i<scope.users.length;i++) {console.log (scope.users[i].name); }    });});

Common Ways to $httpBackend:

Method Description
When (method, URL, [data], [headers]) Test $http ()
Whenget (URL, [headers]); Test $http.get ()

In the same vein, there are Whenhead (), Whendelete () and so on.

Angular $http Services

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.