Describes the use of the $http service in AngularJS

  • 2020-12-16 05:50:22
  • OfStack

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

1. Chain call

The $http service is a function that accepts only one argument, which is an object that contains the configuration content used to generate the HTTP request. This function returns an promise object with both success and error methods.


$http({
url:'data.json',
method:'GET'
}).success(function(data,header,config,status){
// In response to success 
}).error(function(data,header,config,status){
// Processing response failure 
});

2. Return 1 promise object


var promise=$http({
method:'GET',
url:"data.json"
});

Since the $http method returns an promise object, we can use the then method to handle callbacks when the response returns. If you use the then method, you get a special argument that represents the success or failure information for the corresponding object, and you can accept two optional functions as arguments. Or you can use the success and error callbacks instead.


promise.then(function(resp){
//resp is 1 10 response objects 
},function(resp){
// With an error message resp
});

Or this:


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

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

3. Quick get request

(1) $http. get ('/api users. json);

The get() method returns the HttpPromise object.

Can also send such as: delete/head/jsonp/post/put function within acceptable parameters specific refer to page 148

To send jsonp request again for example: in order to send JSONP request, url must contain JSON_CALLBACK.

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 where you pass in a setup object that explains how to construct the XHR object.


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

The setting object can contain the following main keys:

1) method

Can be: GET/DELETE/HEAD/JSONP/POST/PUT

url: Absolute or relative request target
map (string map or object)
The value of this key is a string map or object, which is converted to a query string appended to URL. If the value is not a string, it is serialized by JSON.
Like this:


// Will the parameter be converted to? name=ari In the form of 
$http({
params:{'name':'ari'}
});

data(string or object)

This object contains the data that will be sent to the server as the body of the message. It is usually used when sending POST requests.

Starting with AngularJS 1.3, it can also send base 2 data in POST requests. To send an blob object, you can simply pass it by using the data parameter.
Such as:


var blob=new Blob(['Hello world'],{type:'text/plain'});
$http({
method:'POST',
url:'/',
data:blob
});

4. Response object

The response object that AngularJS passes to the then () method contains four properties.

data

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

status

The HTTP status code for the response

headers

This function is the getter function of the header information and can take one argument to get the corresponding name value

For example, get the value of X-ES145en-ES146en with the following code:


$http({
method: 'GET',
url: '/api/users.json'
}).then (resp) {
//  read X-Auth-ID
resp.headers('X-Auth-ID');
});

config

This object is the complete setup 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, the $http service does not cache the request locally. When sending a separate request, we can enable caching by passing in either a Boolean value or a cache instance to the $http request.


$http.get('/api/users.json',{ cache: true })
.success(function(data) {})
.error(function(data) {});

On the first send, the $http service sends an 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 rather than actually sending an HTTP GET request.

In this example, since caching is enabled, AngularJS uses $cacheFactory by default, a service that AngularJS creates automatically on 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.

So let me give you AngularJS $http.

AngularJS $http is a service that reads data from the web server.

$http.get(url) is the function used to read the 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 articles: