Introduction to the usage of $http services in Angularjs _angularjs

Source: Internet
Author: User
Tags auth

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

1, Chain call

$http Service is a function that accepts only one parameter, which is an object that contains the configuration content used to generate the HTTP request. This function returns a Promise object with success and error two methods.

$http ({
URL: ' Data.json ', method
: ' Get '
}). Success (function (data,header,config,status) {
//Response succeeded
}). Error (function (data,header,config,status) {
//Processing response failed
});

2. Return 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 you use 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 functions as arguments. Alternatively, you can use the success and the error callback instead.

Promise.then (function (resp) {
//resp is a response object
},function (resp) {
//RESP with error message
});

or so:

Promise.success (function (data,status,config,headers) {
//Process successful response
});
Promise.error (function (data,status,hedaers,config) {
//Processing failed response
});

The main difference between the then () method and the other two methods is that it receives the complete response object, while success () and error () are destructors for the response object.

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 acceptable parameters specific Reference 148 page

② to resend the JSONP request for an 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 explain how to construct the Xhr object.

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

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 that is converted to a query string appended to the URL. If the value is not a string, it is serialized by JSON.
Like this:

Parameter will be converted to? The form of Name=ari
$http ({
params:{' name ': ' Ari '}
});

④data (string or object)

This object contains data that will be sent to the server as a message body. 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 Angularjs passed to the then () method contains four properties.

Data

This data represents the converted response body (if a transformation is defined)

Status

The HTTP status code of the response

Headers

This function is the getter function of the header information, which can accept a parameter to get the corresponding name value

For example, use the following code to get the value of X-auth-id:

$http ({method
: ' Get ',
URL: '/api/users.json '
}). Then (RESP) {
//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 state 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 in 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 and does not actually send 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 to make more custom control over the cache used by ANGULARJS, you can replace true with a request to pass in a custom cache instance.

Below gives everybody to say angularjs $http knowledge.

The Angularjs $http is a service for reading data on a Web server.

$http. Get (URL) is a function used to read server data.

Angularjs instance

<div ng-app= "myApp" ng-controller= "Customersctrl" > 
<ul>
<li ng-repeat= "x in Names" >
{ {x.name + ', ' + X.country}}}
</li>
</ul>
</div>
<script>
var app = Angular.module (' myApp ', []);
App.controller (' Customersctrl ', function ($scope, $http) {
$http. Get ("http://www.runoob.com/try/angularjs/ Data/customers_json.php ")
. Success (function (response) {$scope. names = response.records;}
); </script>

Related Article

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.