Simple usage of $http service in Angularjs

Source: Internet
Author: User

We can use the built-in $http service to communicate directly with the outside. $http service simply encapsulates the native XMLHttpRequest object of the browser.

1. Chained calls

The $http service is a function that accepts only one parameter, which is an object that contains the data used to generate the HTTP request.
Configuration content. This function returns a Promise object that has a success and error two methods.
$http ({
URL: ' Data.json ',
Method: ' GET '
}). Success (function (Data,header,config,status) {
Successful response

}). Error (function (data,header,config,status) {
Processing response failed
});

2. Returns a Promise Object
var promise= $http ({
Method: ' GET ',
URL: "Data.json"
});

Because the $http method returns a Promise Object , we can use the then method to handle the callback when the response returns. If
Using the then method, you get a special parameter that represents the success or failure information for the corresponding object, and you can accept two
Optional function as the parameter. Alternatively, you can use the success and error callbacks instead.
promise.then (function (resp) {
RESP is a response object

},function (RESP) {
RESP with error messages

});

or this:
promise.success (function (data,status,config,headers) {
Handling a successful response
});

Promise.error (function (data,status,hedaers,config) {
Response after a failed process
});

then the main difference between the then () method and the other two methods is that it receives the full response object, while success () and error () respond to the
As a destructor.

3. Quick GET Request

① $http. Get ('/api/users.json ');

The Get () method returns the Httppromise object.

can also send for example: delete/head/jsonp/post/put function within the acceptable parameters specific Reference 148 page


② to resend the JSONP request example: in order to send a JSONP request, the URL must contain the Json_callback typeface .

JSONP (url,config) where config is optional

var promise= $http. Jsonp ("/api/users.json?callback=json_callback");


4, you can also use $http as a function, you need to pass in a set object, to illustrate how to construct Xhr object.

$http ({
Method: ' GET ',
URL: '/api/users.json ',
params:{
' username ': ' Tan '
});

  where the Settings object can contain the following primary keys:
 ①method
  can be: get/delete/head/jsonp/post/ PUT
 
 ②url: Absolute or relative request target
 ③params (string map or object)
  The value of this key is a string map or object, will be converted into a query string appended to the URL. If the value is not a string, it is serialized by JSON.
  For example:
 
   //parameters will be converted to? Name=ari form
    $http ({
        params:{' name ': ' Ari '}
   });

 ④data (String or object)
  This object contains data that will be sent to the server as the body of the message. Typically used when sending a POST request.
 
  starting with Angularjs 1.3, it can also send binary data in a POST request. To send a Blob object, you can simply pass it by using the data parameter.
  For example:
var blob=new blob ([' Hello World '],{type: ' Text/plain '});
$http ({
Method: ' POST ',
URL: '/',
Data:blob
});

4. Response Object

The response object passed to the then () method Angularjs contains four properties.
◇data
This data represents the transformed response body (if a conversion is defined)
◇status
HTTP status code for the response
◇headers
This function is the getter function of the header information and can accept a parameter to get the corresponding name value

For example, get the value of X-auth-id with the following code:
$http ({
    Method: ' GET ',
    url: '/api/users.json '

   //Read X-auth-id
    resp.headers (' X-auth-id ');
});

◇config
This object is the complete set object used to generate the original request.

◇statustext (String)
This string is the HTTP status text of the response.

5. Caching HTTP Requests
By default, the $http service does not cache the request locally. When sending a separate request, we can enable caching by passing a Boolean value or a cache instance to the $http request.
$http. Get ('/api/users.json ', { cache:true })
. Success (function (data) {})
. Error (function (data) {});

The first time a request is sent, the $http service sends a GET request to/api/users.json. The second time the same GET request is sent, the $http service retrieves the result of the request from the cache without actually sending an HTTP GET request.
In this example, because the cache is enabled, ANGULARJS uses $cachefactory by default, which is Angularjs created automatically at startup.

If you want more custom control over the cache used by ANGULARJS, you can pass in a custom cache instance to the request instead of true.

Study angular, personal recommendation book "Angularjs authoritative Course"

Simple usage of $http service in Angularjs

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.