SoFunction
Updated on 2025-04-13

A brief discussion on the simple usage of $http service in AngularJS

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

1. Chain call

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

$http({
url:'',
method:'GET'
}).success(function(data,header,config,status){
//Response successfully
}).error(function(data,header,config,status){
//Processing response failed});

2. Return a promise object

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

Since the $http method returns a promise object, we can use the then method to handle the callback when the response is returned. If you use the then method, you will get a special parameter that represents the success or failure information of the corresponding object. You can also accept two optional functions as parameters. Or you can use success and error callbacks instead.

(function(resp){
//resp is a response object
},function(resp){
//Resp with error message
});

Or this:

(function(data,status,config,headers){
//Processing successful response});

(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() destruct the response object.

3. Quick get request

①$('/api/');

The get() method returns the HttpPromise object.

You can also send such as: delete/head/jsonp/post/put. For specific reference to page 148.

②Example the example of sending a jsonp request: In order to send a JSONP request, the url must contain the word JSON_CALLBACK.

jsonp(url,config) where config is optional

var promise=$("/api/?callback=JSON_CALLBACK");

4. You can also use $http as a function. At this time, you need to pass in a setting object to explain how to construct an XHR object.

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

The setting object can contain the following main 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, which will be converted into a query string and appended to the URL. If the value is not a string, it will be serialized by JSON.

For example:

// Will the parameters 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 a message body. Usually used when sending POST requests.

Starting with AngularJS 1.3, it can also send binary data in POST requests. 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 by AngularJS contains four properties.

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

◇status: the response HTTP status code

◇headers: This function is a getter function with header information. It can accept a parameter to obtain the corresponding name value.

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

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

◇config: This object is a 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, the $http service does not cache requests locally. When sending a separate request, we can enable cache by passing a boolean value or a cache instance to the $http request.

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

The first time the request is sent, the $http service will send a GET request to /api/. The second time the same GET request is sent, the $http service will retrieve the result of the request from the cache without actually sending an HTTP GET request.
In this example, because the cache is enabled, AngularJS will use $cacheFactory by default, which is automatically created by AngularJS at startup.

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

Learn angular, the electronic PDF version of the personal recommended book "AngularJS Authoritative Tutorial" is as follows:https:///books/

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.