Introduction to $ http service in AngularJS _ AngularJS

Source: Internet
Author: User
We can use the built-in $ http service to directly communicate with the outside. $ Http service simply encapsulates the native XMLHttpRequest object of the browser. Next, I will give you a brief introduction to http service usage in angularjs. For more information, see the built-in $ http service for external communication. $ Http service simply encapsulates the native XMLHttpRequest object of the browser.

1. chained call

$ Http service can only accept one parameter function. This parameter is an object that contains the configuration content used to generate an HTTP request. This function returns a promise object with two methods: success and error.

$ Http ({url: 'Data. json', method: 'get '}). success (function (data, header, config, status) {// response successful }). error (function (data, header, config, status) {// failed to process response });

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 process the callback in response to the returned result. If the then method is used, a special parameter is obtained, which indicates the success or failure information of the corresponding object. Two optional functions can also be used as parameters. Alternatively, you can use success and error callback instead.

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

Or:

Promise. success (function (data, status, config, headers) {// response to successful processing}); promise. error (function (data, status, hedaers, config) {// response after processing failure });

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

3. Quick get requests

① $ Http. get ('/api/users. json ');

The get () method returns the HttpPromise object.

You can also send acceptable parameters in the delete/head/jsonp/post/put function, for example. For details, refer to page 148.

② Example of sending another jsonp Request: To send a JSONP request, the url must contain the JSON_CALLBACK text.

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. In this case, you need to input a setting object to illustrate how to construct an XHR object.

$http({method:'GET',url:'/api/users.json',params:{'username':'tan'});

The setting object can contain the following key:

① 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, which is converted into a query string and appended to the URL. If the value is not a string, it is serialized in JSON format.
For example:

// The parameter is converted? Name = ari format $ http ({params: {'name': 'ari '}});

④ Data (string or object)

This object contains data that will be sent to the server as a message body. Usually used when sending POST requests.

Starting from AngularJS 1.3, it can also send binary data in the 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 by AngularJS to the then () method contains four attributes.

Data

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

Status

HTTP status code of the response

Headers

This function is the getter function of the header information. It can take a parameter to obtain the corresponding name value.

For example, use the following code to obtain the value of X-Auth-ID:

$ Http ({method: 'get', url: '/api/users. json '}). then (resp) {// read the X-Auth-IDresp.headers ('x-Auth-id ');});

Config

This object is the complete setting object used to generate the original request.

StatusText (string)

This string is the HTTP status text of the response.

5. Cache HTTP requests

By default, $ http does not cache requests locally. When sending a separate request, we can enable the cache 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) {});

When the first request is sent, $ http will send a GET request to/api/users. json. When sending the same GET request for the second time, $ http will retrieve the request result from the cache, instead of sending an http get request.

In this example, AngularJS uses $ cacheFactory by default because caching is enabled. This service is automatically created when AngularJS is started.

If you want to customize the cache used by AngularJS, You can input a custom cache instance to the request instead of true.

The following describes AngularJS $ http knowledge.

AngularJS $ http is a service used to read data from web servers.

$ Http. get (url) is a function used to read server data.

AngularJS instance

  • {{ x.Name + ', ' + x.Country }}

《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.