Call Rest Service In AngularJS

This blog is intended to explain the concept of rest service call in AngularJS.

Introduction

AngularJs provides $http for the communication withthe endpoint by calling Restful endpoint. It issues XHR and JSONP calls. It uses several methods like GET, POST, PUT, DELETE, HEAD, etc.

The $http.GET or $http.POST method accepts any JavaScript object or a string value as the data parameter. It converts the JavaScript data object into JSON String.

Rest Service Call using With $http
  1. myApp.factory('myService', ['$http''$q', function ($http, $q)  
  2. {  
  3.     function getBookData()  
  4.     {  
  5.         var deferred = $q.defer();  
  6.         $http.get('https://myRestServiceUrl').success(function (data)  
  7.         {  
  8.             deferred.resolve(data);  
  9.         }).error(function (err)  
  10.         {  
  11.             console.log('Error retrieving data');  
  12.             deferred.reject(err);  
  13.         });  
  14.         return deferred.promise;  
  15.     }  
  16.     return {  
  17.         getBookData: getBookData  
  18.     };  
  19. }]);  
Use $http Service method into Controller
  1. var myApp = angular.module('myApp', []);  
  2. myApp.controller('myCtrl', ['$scope''myService', function ($scope, myService)  
  3. {  
  4.     function fetchBookDetails()  
  5.     {  
  6.         $scope.isLoading = true;  
  7.         myService.getBookData().then(function (data)  
  8.         {  
  9.             $scope.bookDetails = data.books;  
  10.         });  
  11.     }  
  12.     fetchBookDetails();  
  13.     $scope.getBookDataDetails = function ()  
  14.     {  
  15.         fetchBookDetails();  
  16.     };  
  17. }]);  
$q

$q is a service that helps to run functions asynchronously and it returns value whenan asynchronous task completes the process.
$q includes instances or featurs in the form of $q.defer():

It exposes the associated promise instance as well as APIs that can be used for signaling the successful or unsuccessful completion.

The instance of $q.defer() includesthe  below methods:
  1. resolve:

    It resolves the derived promise.

    Example:
    1. .success(function (data) {  
    2.    deferred.resolve(data);  
    3. })  
  2. reject:

    It rejects the derived promise with the reason $q.reject. 

    Example:
    1. .error(function (err) {  
    2.    console.log('Error retrieving data');  
    3.    deferred.reject(err);  
    4. });  
  3. promise:

    It returns promise after resolving the service response.

    Example:
    1. return deferred.promise;