Friday 13 November 2015

$http service in Angularjs

The $http service is a core Angular service that facilitates communication with the remote HTTP servers via the browser's XMLHttpRequest object or via JSONP.


The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.

The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise.


Example-

$http({ 
method: 'GET', 
url: '/demoUrl' 
}) 
.then(function successCallback(response) { 
// this callback will be called asynchronously 
// when the response is available 
}, 
function errorCallback(response) { 
// called asynchronously if an error occurs 
// or server returns response with an error status. 
});

The response object has following properties:
  1. data{string|Object} – The response body transformed with the transform functions.
  2. status{number} – HTTP status code of the response.
  3. headers{function([headerName])} – Header getter function.
  4. config{Object} – The configuration object that was used to generate the request.
  5. statusText{string} – HTTP status text of the response.
A response status code between 200 and 299 is considered a success status and will result in the success callback being called.
If the response is a redirect, XMLHttpRequest will transparently follow it, meaning that the error callback will not be called for such responses.

Example-

post method in $http-

 $http.post(url, data, config)    
        .success(function (data, status, headers, config)
{         // result in case of success
    })        
     .error(function (data, status, header, config) {   
// result in case of error
         });


No comments:

Post a Comment