$http is one of the best AngularJS tools to inquiry http remote servers, making it possible to complete your apps with webservices (e.g. xml and json). $http is very easy to use and immediately available in AngularJS core libraries (with no need to download any other packages).

Its main feature are the following:

  • it's a native AngularJS library
  • it's easy to use
  • it also provides the $httpProvider tool for a better service configuration
  • it supports XSFR and JSON native calls
  • it supports caching operations (on client side, reducing the number of calls to the endpoint)
  • it easily manages callback procedures for success/failure operations

A basic usage of $http provides an immediate handling of success/failure callback operations:

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

One of the simplest ways to include $http tool, is to use it directly inside a controller. It is a good practice, avoiding such kind of use, and trying to move $http into a re-used service, but if you are just starting to work with this tool, or are implementing a simple application, with no specific scalability issues, you can include it directly inside a Controller. Imagine you need to inquiry a remote service, returning a JSON object containing news, according to the following format:

[  
   {  
      "id":825415,
      "title":"At quam qui nihil alias perferendis consequatur error.",
      "summary":"Et quod et in et impedit temporibus quia iste autem nihil qui excepturi nihil aperiam totam blanditiis voluptatem vero id laudantium consequuntur possimus ut.",
      "timestamp":1408043802000,
      "author":"user16"
   },
   {  
      "id":556512,
      "title":"Libero maiores velit consequatur tenetur qui neque aut consequatur.",
      "summary":"Accusantium sit est suscipit culpa voluptas ut maxime odit sit hic dolore placeat molestias illo similique sapiente omnis autem.",
      "timestamp":1407957402000,
      "author":"user3"
   }
]

You need to perform a GET type call to the endpoint, showing the news via a success callback, or an error message in case of failed call. The following is the needed javascript code:

angular.module('myApp.controllers', [])
  .controller('NewsCtrl', ['$scope', '$http', function($scope, $http) {
	  
	  $scope.results = [];
	  $scope.error = false;
	  	  
	  $scope.getLastNews = function() {
		  $http.get("http://my-news-endpoint").success(function(data){
			  $scope.results = data;
		  }).error(function() {
        $scope.error = "No content available"
      });
	  };

  }]);

The following is the code of your html view:

<div ng-repeat="news in results">
  <h1> news.title </h1>
  <h2> nws.summary </h2>
  <p>published at  news.timestamp </p>
</div>

<div ng-show="error"> error </div>

Among the other $http options, you can set a simple configuration related to the ongoing call. The following is the possible setting of parameters:

method - {string} - HTTP method (e.g. 'GET', 'POST', etc)
url - {string} - Absolute or relative URL of the resource that is being requested.
params - {Object.<string|Object>} - Map of strings or objects which will be turned to?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified.
data - {string|Object} - Data to be sent as the request message data.
headers - {Object} - Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent.
xsrfHeaderName - {string} - Name of HTTP header to populate with the XSRF token.
xsrfCookieName - {string} - Name of cookie containing the XSRF token.
transformRequest - {function(data, headersGetter)|Array.<function(data, headersGetter)>} - transform function or an array of such functions. The transform function takes the http request body and headers and returns its transformed (typically serialized) version.
transformResponse - {function(data, headersGetter)|Array.<function(data, headersGetter)>} - transform function or an array of such functions. The transform function takes the http response body and headers and returns its transformed (typically deserialized) version.
cache - {boolean|Cache} - If true, a default $http cache will be used to cache the GET request, otherwise if a cache instance built with $cacheFactory, this cache will be used for caching.
timeout - {number|Promise} - timeout in milliseconds, or promise that should abort the request when resolved.
withCredentials - {boolean} - whether to set the withCredentials flag on the XHR object. See requests with credentials for more information.
responseType - {string} - see requestType.

In our next articles on such topics, we will talk about the setting of more advanced configurations and the usage of authentication headers. 

Gabriele Mittica

Developer at Corley S.r.l , Website , Git home page , @gabrielemittica , Linkedin profile
Passionate startupper, Cloud developer and amstaff lover. Worldwide geekka traveler!

All articles by Gabriele Mittica

Comments

comments powered by Disqus

cloudparty

Follow Us