Back-End Server Communication With AngularJS

Introduction

AngularJS is very good to communicate with various back-ends using with features XMLHttpRequest (XHR) and JSONP requests. It has very common $http service for the XHR and JSON calls. It can easily handle Restful endpoints.
 
What is Rest
 
Rest stands for Representational State Transfer. It is an architectural style. It specifies constraints, such as the uniform interface. It can use SOAP web services but doesn't define too much standards like SOAP. It requires less bandwidth resources than SOAP.  Data format can be in the form of plain text, HTML, XML, JSON, etc.
 
XHR
 
XHR stands for XMLHTTPRequest. It is an API and provides facility to make a HTTP or HTTPS calls to a web server and to provide data in return.

JSON

It stands for JavaScript Object Notation. It removes  the cross-domain restrictions in browser. It provides data in a format where object fields are represented as key-value pairs like below:
  1. {  
  2.     "EmpName""Tom",  
  3.     "EmpId": 1234,  
  4.     "City": Delhi  
  5. }  

$http very basic

AngularJS provides $http service to make XHR and JSON calls.  It is very simple and straightforward like below: 
  1. var myResponse = $http.get('myData.json');  
  2.   
  3. myResponse.success(function (data, status, headers, config) {  
  4.    $scope.data = data;  
  5. });  
  6.   
  7. myResponse.error(function (data, status, headers, config) {  
  8.        throw new Error('Error in retrieving data...');  
  9. });  

Methods fo XHRrequests

Below are some methods of XHRrequests:
  1. GET: $http.get(url, config)
  2. POST:  $http.post(url, data, config)
  3. PUT: $http.put(url, data, config)
  4. DELETE : $http.delete(url, config)
  5. HEAD: $http.head
Http Responses
 
Whenever we make a API call using $http then requests can be either success or fail. So, in the case of response, method will be called with the following parameters :
  1. Data : It is an actual response data.
  2. Status: It is the HTTP status of the response.
  3. Headers
  4. Config: It is a configuration object that was supplied when request was made.

$q

$q is a service that helps us to run function asynchronously. We use its return value when it completes the processing of asynchronous operation.

$q.defer()

It creates new instance of deferred. It exposes the associated promise instance as well as APIs which are being used in the case of success or failure. 
 
The following are the methods:
  1. resolve(value) : It resolves the derived promise with the value.  e.g. 
    1. var defer = $q.defer();  
    2.   
    3. ....  
    4.   
    5. defer.resolve(data);  

  2.  reject(reason): It rejects the derived promise with the reason. e.g. 
    1.  var defer = $q.defer();       
    2.   
    3. ....  
    4.    
    5. .error(function () {  
    6.         defer.reject();  
    7.       });  

  3.  notify(value): It provides updates on the status of the promise's execution. 
Complete example
  1. function myServiceRequest() 
  2. {  
  3.     var defer = $q.defer();  
  4.     $http.get('abc.json')  
  5.       .success(function (data)
  6.        {  
  7.         defer.resolve(data);  
  8.       })  
  9.       .error(function ()
  10.        {  
  11.         defer.reject();  
  12.       });  
  13.          
  14.     return defer.promise;  
  15.   }  

Complete wrapper for API call using $http with exception handling

  1. /*global angular*/  
  2.   
  3. angular.module('myModule').service('myDataService',  
  4.     [  
  5.         '$http',  
  6.         '$q',  
  7.         '$log',  
  8.         function (  
  9.             $http,  
  10.             $q,  
  11.             $log  
  12.         ) {  
  13.             'use strict';  
  14.             var self = this;  
  15.   
  16.             self.get = function (url, data, parseJson) {  
  17.                 var deferred = $q.defer(), startTime = new Date(),  
  18.                     getData = { params: data };  
  19.                 $http.get(url, getData).success(function (data, status, header, config) {  
  20.                     /*jslint unparam:true*/  
  21.                     var endTime = new Date();  
  22.                     $log.log(url, status, endTime - startTime, "ms");  
  23.                     if (parseJson) {  
  24.                         deferred.resolve(angular.fromJson(data.d));  
  25.                     } else {  
  26.                         deferred.resolve(data.d);  
  27.                     }  
  28.                 }).error(function (data, status, header, config) {  
  29.                     /*jslint unparam:true*/  
  30.                     var endTime = new Date();  
  31.                     $log.log(url, status, endTime - startTime, "ms");  
  32.                 });  
  33.                 return deferred.promise;  
  34.             };  
  35.   
  36.             self.post = function (url, data, parseJson) {  
  37.                 var deferred = $q.defer(), startTime = new Date();  
  38.                 $http.post(url, data).success(function (data, status, header, config) {  
  39.                     /*jslint unparam:true*/  
  40.                     var endTime = new Date();  
  41.                     $log.log(url, status, endTime - startTime, "ms");  
  42.                     if (parseJson) {  
  43.                         deferred.resolve(angular.fromJson(data.d));  
  44.                     } else {  
  45.                         deferred.resolve(data.d);  
  46.                     }  
  47.                 }).error(function (data, status, header, config) {  
  48.                     /*jslint unparam:true*/  
  49.                     var endTime = new Date();  
  50.                     $log.log(url, status, endTime - startTime, "ms");  
  51.                 });  
  52.                 return deferred.promise;  
  53.             };  
  54.         }]);  
Call post method from myDataService
  1. /*global angular*/  
  2. angular.module('myModule').service('myPersonalService', ['$log''myDataService''urlConstants',  
  3.     function ($log, dataService, urlConstants) {  
  4.         'use strict';  
  5.         $log.log("myPersonalService details");  
  6.   
  7.         var self = this;  
  8.         self.myMethod = function (myId) {  
  9.             var param = {  
  10.                 myId: myId  
  11.             };  
  12.             return myDataService.post(urlConstants.myMethodUrl, param);  
  13.         };  
  14.           
  15.     }]); 

X

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

Start Learning Now