AngularJS From Beginning: Http Request or Ajax - Part Seven

I am here to continue the discussion around AngularJS. Today, we will discuss about the $http service with AngularJS. Also in case you have not had a look at our previous articles of this series, go through the following links:

In this article, we will discuss about the built-in AngularJS service for making ajax request and representing asynchronous activities.

Why to use Ajax Services

Ajax is the foundation of the modern web application, and you will use the services that I describe in this article every time that you need to communicate with a server without causing the browser to load new content and, in doing so, dump your AngularJS application. That said, if you are consuming data from a RESTful API, then you should use the $resource service. I will describe REST and $resource in the next article, but the short version is that $resource provides a higher-level API that is built on the services I describe in this article and makes it easier to perform common data operations.

Making Ajax Requests

The $http service is used to make and process Ajax requests, which are standard HTTP requests that are performed asynchronously. Ajax is at the heart of modern web applications, and the ability to request content and data in the background while the user interacts with the rest of the application is an important way of creating a rich user experience. There are two ways to make a request using the $http service. The first—and most common—is to use one of the convenience methods that the service defines, which I have described in below table and which allows you to make requests using the most commonly needed HTTP methods. All of these methods accept an optional configuration object, which I describe in the “Configuring Ajax Requests” section later in this article.

Name

Descriptions

get(url, config)

Performs a GET request for the specified URL.

post(url, data, config)

Performs a POST request to the specified URL to submit the specified data.

delete(url, config)

Performs a DELETE request to the specified URL.

put(url, data, config)

Performs a PUT request with the specified data and URL.

patch(url, data, config)

Performs a PATCH request with the specified data and URL.

head(url, config)

Performs a HEAD request to the specified URL.

jsonp(url, config)

Performs a GET request to obtain a fragment of JavaScript code that is then executed. JSONP, which stands for JSON with Padding, is a way of working around the limitations that browsers apply to where JavaScript code can be loaded from.

The other way to make an Ajax request is to treat the $http service object as a function and pass in a configuration object. This is useful when you require one of the HTTP methods for which there is not a convenience method available. You pass in a configuration object that includes the HTTP method you want to use. I’ll discuss about how to make Ajax requests in this way in the next article where I discuss about RESTful services, but in this article I am going to focus on the convenience methods.

Receiving Ajax Responses

Making a request is only the first part of the Ajax process, and I also have to receive the response when it is ready. The A in Ajax stands for asynchronous, which means that the request is performed in the background, and you will be notified when a response from the server is received at some point in the future. AngularJS uses a JavaScript pattern called promises to represent the result from an asynchronous operation, such as an Ajax request. A promise is an object that defines methods that you can use to register functions that will be invoked when the operation is complete. The promise objects returned from the $http methods in above table define the methods shown in below.

Name

Descriptions

success(fn)

Invokes the specified function when the HTTP request has successfully completed

error(fn)

Invokes the specified function when the request does not complete successfully

then (fn,fn)

Registers a success function and an error function

The success and error methods pass their functions a simplified view of the response from the server. The success function is passed the data that the server sends, and the error function is passed a string that describes the problem that occurred. Further, if the response from the server is JSON data, then AngularJS will parse the JSON to create JavaScript objects and pass them to the success function automatically.

Getting More Response Details

Using the then method on the promise object allows you to register both a success and error function in a single method call. But also, more importantly, it provides access to more detailed information about the response from the server. The object that the then method passes to its success and error functions defines the properties I have described in below table.

Name

Descriptions

data

Returns the data from the request

status

Returns the HTTP status code returned by the server

headers

Returns a function that can be used to obtain headers by name

config

The configuration object used to make the request (see the “Configuring Ajax Requests” section for details)

 
For demonstrate the above concept, we first create a json data and then load those data using ajax request.
 
data.json 
  1. [  
  2.     {  
  3.         "Category""ASP.NET",  
  4.         "Book""Mastering ASP.Net 5",  
  5.         "Publishers""Wrox Publication",  
  6.         "Price": 500.00  
  7.     },  
  8.     {  
  9.         "Category""MVC",  
  10.         "Book""Professional MVC 5",  
  11.         "Publishers""Wrox Publication",  
  12.         "Price": 750.00  
  13.     },  
  14.     {  
  15.         "Category""JQuery",  
  16.         "Book""ABCD of JQuery",  
  17.         "Publishers""BPB Publication",  
  18.         "Price": 500.00  
  19.     }  
  20. ]  
App.js
  1. var testApp = angular.module('TestApp', []);  
Ajax.html
  1. <!DOCTYPE html>  
  2. <html ng-app="TestApp">  
  3. <head>  
  4.     <title>AngularJS AJax </title>  
  5.     <script src="angular.js"></script>  
  6.     <link href="../../RefStyle/bootstrap.min.css" rel="stylesheet" />  
  7.     <script src="app.js"></script>  
  8.     <script src="ajax.js"></script>  
  9.   
  10. </head>  
  11. <body ng-controller="ajaxController">  
  12.     <div class="panel panel-default">  
  13.         <div class="panel-body">  
  14.             <table class="table table-striped table-bordered">  
  15.                 <thead><tr><th>Name</th><th>Category</th><th>Price</th></tr></thead>  
  16.                 <tbody>  
  17.                     <tr ng-hide="products.length">  
  18.                         <td colspan="4" class="text-center">No Data</td>  
  19.                     </tr>  
  20.                     <tr ng-repeat="item in products">  
  21.                         <td>{{item.Category}}</td>  
  22.                         <td>{{item.Book}}</td>  
  23.                         <td>{{item.Publishers}}</td>  
  24.                         <td>{{item.price | currency}}</td>  
  25.                     </tr>  
  26.                 </tbody>  
  27.             </table>  
  28.             <p>  
  29.                 <button class="btn btn-primary" ng-click="loadData()">  
  30.                     Load Data  
  31.                 </button>  
  32.                 <button class="btn btn-primary" ng-click="loadDataPromise()">  
  33.                     Load Data With Promise  
  34.                 </button>                  
  35.             </p>  
  36.         </div>  
  37.     </div>  
  38. </body>  
  39. </html>  
Ajax.js
  1. testApp.controller("ajaxController"function ($scope, $http) {  
  2.   
  3.     $scope.loadData = function () {  
  4.         $http.get("data.json").success(function (data) {  
  5.             $scope.products = data;  
  6.         });  
  7.     }  
  8.   
  9.     $scope.loadDataPromise = function () {  
  10.         $http.get("data.json").then(function (response) {  
  11.             console.log("Status: " + response.status);  
  12.             console.log("Type: " + response.headers("content-type"));  
  13.             console.log("Length: " + response.headers("content-length"));  
  14.             $scope.products = response.data;  
  15.         });  
  16.     }  
  17. });  
The output of the above code is,


Processing Other Data Types

Although obtaining JSON data is the most common use for the $http service, you may not always have the luxury of working with a data format that AngularJS will process automatically. If this is the case, then AngularJS will pass the success function an object containing the properties discussed above and you will be responsible for parsing the data. To give you a simple example of how this works, I created a simple XML file called productData.xml that contains the same product information as the previous example, but expressed as a fragment of XML.

Data.xml
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <products>  
  3.   <product Category="NodeJs" Book="Beginning of NodeJs" Publishers="BPB Publication" Price="500" />  
  4.   <product Category="ASP>Net" Book="Mastering ASP.Net 4" Publishers="Wrox Publication" Price="700" />  
  5.   <product Category="MVC" Book="Professional MVC 6" Publishers="Wrox Publication" Price="500" />  
  6. </products>  
Now add another button in the ajax.html file for load the data from xml file and change the ajax.js file code as below,
  1. testApp.controller("ajaxController"function ($scope, $http) {  
  2.   
  3.     $scope.loadData = function () {  
  4.         $http.get("data.json").success(function (data) {  
  5.             $scope.products = data;  
  6.         });  
  7.     }  
  8.   
  9.     $scope.loadDataPromise = function () {  
  10.         $http.get("data.json").then(function (response) {  
  11.             console.log("Status: " + response.status);  
  12.             console.log("Type: " + response.headers("content-type"));  
  13.             console.log("Length: " + response.headers("content-length"));  
  14.             $scope.products = response.data;  
  15.         });  
  16.     }  
  17.   
  18.     $scope.loadXMLData = function () {  
  19.         $http.get("data.xml").then(function (response) {  
  20.             $scope.products = [];  
  21.             var productElems = angular.element(response.data.trim()).find("product");  
  22.             for (var i = 0; i < productElems.length; i++) {  
  23.                 var product = productElems.eq(i);  
  24.                 $scope.products.push({  
  25.                     Category: product.attr("Category"),  
  26.                     Book: product.attr("Book"),  
  27.                     Publishers: product.attr("Publishers"),  
  28.                     price: product.attr("price")  
  29.                 });  
  30.             }  
  31.         });  
  32.     }  
  33. });  

Configuring Ajax Requests

The methods defined by the $http service all accept an optional argument of an object containing configuration settings. For most applications, the default configuration used for Ajax requests will be fine, but you can adjust the way the requests are made by defining properties on the configuration object corresponding to below table.

Name

Descriptions

data

Sets the data sent to the server. If you set this to an object, AngularJS will serialize it to the JSON format.

headers

Used to set request headers. Set headers to an object with properties whose names and values correspond to the headers and values you want to add to the request.

method

Sets the HTTP method used for the request.

params

Used to set the URL parameters. Set params to an object whose property names and values correspond to the parameters you want to include.

timeout

Specifies the number of milliseconds before the request expires. transformRequest Used to manipulate the request before it is sent to the server

transformResponse

Used to manipulate the response when it arrives from the server

url

Sets the URL for the request.

withCredentials

When set to true, the withCredentials option on the underlying browser request object is enabled, which includes authentication cookies in the request.

The most interesting configuration feature is the ability to transform the request and response through the aptly named transformRequest and transformResponse properties. AngularJS defines two built-in transformations; outgoing data is serialized into JSON, and incoming JSON data is parsed into JavaScript objects.

Html file code
  1. <!DOCTYPE html>  
  2. <html ng-app="TestApp">  
  3. <head>  
  4.     <title>AngularJS AJax </title>  
  5.     <script src="angular.js"></script>  
  6.     <link href="../../RefStyle/bootstrap.min.css" rel="stylesheet" />  
  7.     <script src="app.js"></script>  
  8.     <script src="ajax_config.js"></script>  
  9.   
  10. </head>  
  11. <body ng-controller="ajaxController">  
  12.     <div class="panel panel-default">  
  13.         <div class="panel-body">  
  14.             <table class="table table-striped table-bordered">  
  15.                 <thead><tr><th>Name</th>  
  16.                     <th>Category</th>  
  17.                     <th>Price</th></tr></thead>  
  18.                 <tbody>  
  19.                     <tr ng-hide="products.length">  
  20.                         <td colspan="4" class="text-center">No Data</td>  
  21.                     </tr>  
  22.                     <tr ng-repeat="item in products">  
  23.                         <td>{{item.Category}}</td>  
  24.                         <td>{{item.Book}}</td>  
  25.                         <td>{{item.Publishers}}</td>  
  26.                         <td>{{item.price | currency}}</td>  
  27.                     </tr>  
  28.                 </tbody>  
  29.             </table>  
  30.             <p>  
  31.                 <button class="btn btn-primary" ng-click="loadData()">  
  32.                     Load Data  
  33.                 </button>  
  34.                 <button class="btn btn-primary" ng-click="loadXMLData()">  
  35.                     Load Data (XML)  
  36.                 </button>  
  37.             </p>  
  38.         </div>  
  39.     </div>  
  40. </body>  
  41. </html>  
AngularJS file code
  1. testApp.controller("ajaxController"function ($scope, $http) {  
  2.   
  3.     $scope.loadData = function () {  
  4.         $http.get("data.json").success(function (data) {  
  5.             $scope.products = data;  
  6.         });  
  7.     }  
  8.   
  9.     $scope.loadXMLData = function () {  
  10.         var config = {  
  11.             transformResponse: function (data, headers) {  
  12.                 if ((headers("content-type") == "application/xml" || headers("content-type") == "text/xml") && angular.isString(data)) {  
  13.                     products = [];  
  14.                     var productElems = angular.element(data.trim()).find("product");  
  15.                     for (var i = 0; i < productElems.length; i++) {  
  16.                         var product = productElems.eq(i);  
  17.                         products.push({  
  18.                             Category: product.attr("Category"),  
  19.                             Book: product.attr("Book"),  
  20.                             Publishers: product.attr("Publishers"),  
  21.                             price: product.attr("price")  
  22.                         });  
  23.                     }  
  24.                     return products;  
  25.                 } else {  
  26.                     return data;  
  27.                 }  
  28.             }  
  29.         }  
  30.         $http.get("data.xml", config).success(function (data) {  
  31.             $scope.products = data;  
  32.         });  
  33.     }  
  34. });  
Transforming a Request

You can transform a request by assigning a function to the transformRequest property of the configuration object. The function is passed the data that will be sent to the server and a function that returns header values (although many headers will be set by the browser just before it makes the request). The result returned by the function will be used for the request, which provides the means for serializing data.

Html file code,
  1. <!DOCTYPE html>  
  2. <html ng-app="TestApp">  
  3. <head>  
  4.     <title>AngularJS AJax </title>  
  5.     <script src="angular.js"></script>  
  6.     <link href="../../RefStyle/bootstrap.min.css" rel="stylesheet" />  
  7.     <script src="app.js"></script>  
  8.     <script src="ajax_transforms.js"></script>  
  9.   
  10. </head>  
  11. <body ng-controller="ajaxController">  
  12.     <div class="panel panel-default">  
  13.         <div class="panel-body">  
  14.             <table class="table table-striped table-bordered">  
  15.                 <thead><tr><th>Name</th><th>Category</th><th>Price</th></tr></thead>  
  16.                 <tbody>  
  17.                     <tr ng-hide="products.length">  
  18.                         <td colspan="4" class="text-center">No Data</td>  
  19.                     </tr>  
  20.                     <tr ng-repeat="item in products">  
  21.                         <td>{{item.Category}}</td>  
  22.                         <td>{{item.Book}}</td>  
  23.                         <td>{{item.Publishers}}</td>  
  24.                         <td>{{item.price | currency}}</td>  
  25.                     </tr>  
  26.                 </tbody>  
  27.             </table>  
  28.             <p>  
  29.                 <button class="btn btn-primary" ng-click="loadData()">  
  30.                     Load Data  
  31.                 </button>  
  32.                 <button class="btn btn-primary" ng-click="sendData()">Send Data</button>  
  33.             </p>  
  34.         </div>  
  35.     </div>  
  36. </body>  
  37. </html>  
Angularjs file code,
  1. testApp.controller("ajaxController"function ($scope, $http) {  
  2.   
  3.     $scope.loadData = function () {  
  4.         $http.get("data.json").success(function (data) {  
  5.             $scope.products = data;  
  6.         });  
  7.     }  
  8.   
  9.     $scope.sendData = function () {  
  10.         var config = {  
  11.             headers: {  
  12.                 "content-type""application/xml"  
  13.             },  
  14.             transformRequest: function (data, headers) {  
  15.                 var rootElem = angular.element("<xml>");  
  16.                 for (var i = 0; i < data.length; i++) {  
  17.                     var prodElem = angular.element("<product>");  
  18.                     prodElem.attr("Category", data[i].Category);  
  19.                     prodElem.attr("Book", data[i].Book);  
  20.                     prodElem.attr("Book", data[i].Book);  
  21.                     prodElem.attr("Publishers", data[i].Publishers);  
  22.                     rootElem.append(prodElem);  
  23.                 }  
  24.                 rootElem.children().wrap("<products>");  
  25.                 return rootElem.html();  
  26.             }  
  27.         }  
  28.         $http.post("ajax_transforms.html", $scope.products, config);  
  29.     }  
  30. });  
The output of the code is as below,

Working with Promises

Promises are a way of registering interest in something that will happen in the future, such as the response sent from a server for an Ajax request. Promises are not unique to AngularJS, and they can be found in many different libraries, including jQuery, but there are variations between implementations to accommodate differences in design philosophy or the preferences of the library developers. There are two objects required for a promise: a promise object, which is used to receive notifications about the future outcome, and a deferred object, which is used to send the notifications. For most purposes, the easiest way to think of promises is to regard them as a specialized kind of event; the deferred object is used to send events via the promise objects about the outcome of some task or activity. AngularJS provides the $q service for obtaining and managing promises, which it does through the methods that I have described in below table. In the sections that follow, I’ll show you how the $q service works as I build out the example application.

Name

Descriptions

all(promises)

Returns a promise that is resolved when all of the promises in the specified array are resolved or any of them is rejected

defer()

Creates a deferred object

reject(reason)

Returns a promise that is always rejected

when(value)

Wraps a value in a promise that is always resolved (with the specified value as a result)

We can define the deferred object with the help of $q.defer method and a deferred object defines the methods as below,

Name

Descriptions

resolve(result)

Signals that the deferred activity has completed with the specified value

reject(reason)

Signals that the deferred activity has failed or will not be completed for the specified reason

notify(result)

Provides an interim result from the deferred activity

promise

Returns a promise object that receives the signals from the other methods

The main pattern of use is to get a deferred object and then call the resolve or reject method to signal the outcome of the activity.

The promise objects defines the below methods,

Name

Descriptions

then(success, error, notify)

Registers functions that are invoked in response to the deferred object’s resolve, reject, and notify methods. The functions are passed the arguments that were used to call the deferred object’s methods.

catch(error)

Registers just an error handling function, which is passed the argument used to call the deferred object’s reject method.

finally(fn)

Registers a function that is invoked irrespective of the promise being resolved or rejected. The function is passed the argument used to call the deferred object’s resolve or reject method.

 
Promise.html 
  1. <!DOCTYPE html>  
  2. <html ng-app="TestApp">  
  3. <head>  
  4.     <title>AngularJS AJax Promise </title>  
  5.     <script src="angular.js"></script>  
  6.     <link href="../../RefStyle/bootstrap.min.css" rel="stylesheet" />  
  7.     <script src="app.js"></script>  
  8.     <script src="promise.js"></script>  
  9.   
  10. </head>  
  11. <body ng-controller="ajaxController">  
  12.     <div class="well" promise-worker>  
  13.         <button class="btn btn-primary">Heads</button>  
  14.         <button class="btn btn-primary">Tails</button>  
  15.         <button class="btn btn-primary">Abort</button>  
  16.         Outcome: <span promise-observer></span>  
  17.     </div>  
  18. </body>  
  19. </html>  
Promise.js
  1. testApp.directive("promiseWorker"function($q) {  
  2.     var deferred = $q.defer();  
  3.     return {  
  4.         link: function(scope, element, attrs) {  
  5.             element.find("button").on("click"function (event) {  
  6.                 var buttonText = event.target.innerText;  
  7.                 if (buttonText == "Abort") {  
  8.                     deferred.reject("Aborted");  
  9.                 } else {  
  10.                     deferred.resolve(buttonText);  
  11.                 }  
  12.             });  
  13.         },  
  14.         controller: function ($scope, $element, $attrs) {  
  15.             this.promise = deferred.promise;  
  16.         }  
  17.     }  
  18. });  
  19.   
  20. testApp.directive("promiseObserver"function () {  
  21.     return {  
  22.         require: "^promiseWorker",  
  23.         link: function (scope, element, attrs, ctrl) {  
  24.             ctrl.promise.then(function (result) {  
  25.                 element.text(result);  
  26.             }, function (reason) {  
  27.                 element.text("Fail (" + reason + ")");  
  28.             });  
  29.         }  
  30.     }  
  31. });  
  32.   
  33. testApp.controller("ajaxController"function ($scope, $http) {  
  34.   
  35.       
  36. });  
The output of the controller is as below,

 
 

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now