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
- myApp.factory('myService', ['$http', '$q', function ($http, $q)
- {
- function getBookData()
- {
- var deferred = $q.defer();
- $http.get('https://myRestServiceUrl').success(function (data)
- {
- deferred.resolve(data);
- }).error(function (err)
- {
- console.log('Error retrieving data');
- deferred.reject(err);
- });
- return deferred.promise;
- }
- return {
- getBookData: getBookData
- };
- }]);
Use $http Service method into Controller
- var myApp = angular.module('myApp', []);
- myApp.controller('myCtrl', ['$scope', 'myService', function ($scope, myService)
- {
- function fetchBookDetails()
- {
- $scope.isLoading = true;
- myService.getBookData().then(function (data)
- {
- $scope.bookDetails = data.books;
- });
- }
- fetchBookDetails();
- $scope.getBookDataDetails = function ()
- {
- fetchBookDetails();
- };
- }]);
$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:
- resolve:
It resolves the derived promise.
Example:
- .success(function (data) {
- deferred.resolve(data);
- })
- reject:
It rejects the derived promise with the reason $q.reject.
Example:
- .error(function (err) {
- console.log('Error retrieving data');
- deferred.reject(err);
- });
- promise:
It returns promise after resolving the service response.
Example: