Built-In And Custom AngularJS Services With Examples

This article will demonstrate built-in AngularJS Services as well as how you can create your own custom service in an AngularJS. This article begins with a brief introduction to AngularJS Services. Afterwards, it demonstrates built-in AngularJS Service with syntax and links to an example on Plunker Editor. Finally, the article discusses custom AngularJS Services.

AngularJS Services 

AngularJS Services are re-usable components or the objects, which have the methods and the properties to perform some business logic and can be used throughout your Application. To use an AngularJS Service in controller, filter, Service and Directive; just add it as a dependency. Angular comes with some built-in Services but you can create your own custom Service as well.

Built-in AngularJS Service

AngularJS built-in services always start with  a $ sign. Some of the commonly used built-in Services are shown below.
  • $http
  • $resource
  • $q
  • $anchorSrcoll
  • $cacheFactory
  • $locale
  • $timeout
  • $cookies 
  • $routeProvider
  • $routeParams
  • $log
$http

This Service is used to communicate with the Servers over the network; i.e., you can send raw requests like getting and posting the data etc., and to recieve the resposne from the remote Server through this Service.

Syntax
  1. var app=angular.module('app',[]);    
  2. app.controller('mycontroller',['$http',function($http){    
  3.     
  4. //$http get method    
  5.    $http({        
  6.            method: 'GET',        
  7.            url: '/someUrl'        
  8.            //other properties  
  9.          }).then(function successCallback(response) {        
  10.                 // this callback will be called asynchronously        
  11.                 // when the response is available        
  12.            }, function errorCallback(response) {        
  13.                 // called asynchronously if an error occurs        
  14.                 // or server returns response with an error status.        
  15.         });      
  16.     
  17. //$http get shortcut method      
  18.    $http.get('/someUrl').then(function successCallback(response) {    
  19.                // this callback will be called asynchronously    
  20.                // when the response is available    
  21.             }, function errorCallback(response) {    
  22.                // called asynchronously if an error occurs    
  23.                // or server returns response with an error status.    
  24.         });    
  25.     
  26. }]);     
 
$resource

$resource is used for the same purpose as $http Service but the key difference between them is that $resource is based on a RESTful architecture and is used to access Restful Web Services. For using $resource Service, you just need to add Angular-resource script file after AngularJS and dependency of ngResource into Angular module, as shown in the syntax given below.
 
Syntax
  1. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>//angulrJS file    
  2. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular-resource.js"></script>//ngresource file    
  3. <script src="your script file"></script>    
  4.     
  5.     
  6. var app=angular.module('app',['ngResource']);      
  7. app.controller('mycontroller',['$resource',function($resource){      
  8.       
  9. //resource get method      
  10.    $resource('/someURL').get().$promise.then(function(data){    
  11.                   //do some stuff    
  12.        
  13.                },function(response){    
  14.                   //do some stuff    
  15.              });    
  16.       
  17. }]);    
 
$q

$q service is used to handle the promises and the deferred objects. Promises are the pending results of the asynchronous calls and deferred objects returns promises and the results of asychronous operation after its completion to the calling code.

How $q works

Step 1

The client sends asynchronous call to the Service.

Step 2

The Service receives the call and create a deferred object by using $q Service.

Step 3

The deferred object returns the promise to the client.

Step 4

The client uses this promise to write callback functions.

Step 5

The Service performs the work and return the status of the function, which is either successfully completed or rejected through deffered object to the client.

Step 6

The client executes success or an error callback function, which is based on the result return from the Service. 

Syntax
  1. var myApp = angular.module('myApp', []);    
  2.      
  3. //service create deffered object and return promise      
  4. myApp.service('myService',['$q',function($q) {           
  5.           
  6.     //create a deffered object          
  7.     var defferedObject = $q.defer();          
  8.           
  9.     //this method calls when work is being performed         
  10.     defferedObject.notify('notification messages');          
  11.         
  12.     //this method calls when something goes wrong        
  13.     //and errors send back to the client        
  14.     defferedObject.reject('Error Message');        
  15.         
  16.    //this mehod calls when the require        
  17.    //work has completed successfuly        
  18.    //and results are returned to client        
  19.    defferedObject.resolve(data);          
  20.           
  21.    //return promise to caller          
  22.    return defferedObject.promise;          
  23.       
  24.   }]);          
  25.       
  26. myApp.controller('myController',['myService',function(myService){    

  27.    //code receive the promise      
  28.    //and write callback functions      
  29.    //these callback functions receive the result from the service      
  30.    myFunction().then(successCallBack, errorCallBack, notificationCallBack);      
  31.       
  32.    function successCallBack(data) {      
  33.       //do some stuff with data      
  34.    }      
  35.       
  36.    function errorCallBack(error) {      
  37.       //do some stuff      
  38.    }      
  39.       
  40.    function notificationCallBack(notification) {       
  41.       //do some stuff     
  42.    }      

  43. }]);    
Plunker- $q Service Example 
 
$anchorScroll

$anchorScroll service is used to navigate or scroll within the page.
 
Syntax
  1. var myApp=angular.module('myApp', [])  
  2. myApp.controller('ScrollController', ['$scope''$location''$anchorScroll',  
  3.   function($scope, $location, $anchorScroll) {  
  4.     $scope.gotoBottom = function() {  
  5.       // set the location.hash to the id of  
  6.       // the element you wish to scroll to.  
  7.       $location.hash('bottom');  
  8.   
  9.       // call $anchorScroll()  
  10.       $anchorScroll();  
  11.     };  
  12.   }]);   
 
$cacheFactory

$cacheFactory Service is used to cache the data. This Service provides functions through which you can define the capacity of the data objects or the items to be cached, get cache information, put and get the data from cache.
 
Syntax
  1. var myApp=angular.module('myApp', []);    
  2. myApp.controller('CacheController', ['$scope''$cacheFactory'function($scope, $cacheFactory) {    
  3.   //Create Cache of capacity(optional) 3  
  4.   $scope.cache = $cacheFactory('cacheId',{capacity:3});    
  5.   
  6.    //put data into cache  
  7.    $scope.cache.put(key,value);    

  8.    //get data from cache  
  9.    $scope.cache.get(key);  

  10.    //get cache info  
  11.    $scope.cache.info();  
  12.   
  13. }]);    
 
 $locale

$locale Service is used for localization, which is based on the date and numeric formatting. Go to the URL https://code.angularjs.org/1.5.6/i18n/, choose the localization file and add it to your project.

Syntax
  1. var myApp = angular.module('myApp', []);    
  2. myApp.controller('localeController', ['$scope','$locale'function($scope,$locale) {    
  3.   
  4.       //full date format   
  5.       $scope.myFormat=$locale.DATETIME_FORMATS.fullDate;    

  6.       //short date format  
  7.       $scope.myFormat=$locale.DATETIME_FORMATS.fullDate;  
  8. }]);    
Plunker- $locale Example  
 
$timeout

$timeout Service evaluates some expression or calls a function after some delay. It takes two parameters, where one is the function which is to be called and second is the amount of delay in miliseconds before executing the function.

Syntax
  1. var myApp = angular.module('myApp', []);  
  2. myApp.controller('timeoutController', ['$scope''$timeout'function($scope, $timeout) {  
  3.   
  4.   $timeout(function() {  
  5.     //do some stuff
  6.   }, 5000);  
  7.   
  8. }]);  
Plunker-$timeout Example 
 
$cookies

$cookies Service provides an access to the Browser cookies. You can keep the data and get the data fom the Browser cookies. For using $cookies Service, you just need to add Angular-cookies script file after AngularJS and dependency of ngCookies into Angular module, as shown below.

Syntax
  1. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.2/angular.js"></script>  
  2. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.2/angular-cookies.js"></script>  
  3. <script src="your script file"></script>  
  4.   
  5. var myApp=angular.module('myApp'['ngCookies'])    
  6. .controller('cookiesController', ['$cookies'function($cookies) {    
  7.         
  8.      // Retrieving a cookie    
  9.      var myCookie = $cookies.get('myCookieName');    
  10.      
  11.      // Setting a cookie    
  12.      $cookies.put('myCookieName''cookie Value');    
  13.    
  14.      //Removing a cookie  
  15.      $cookies.remove('myCookieName');   
  16.   
  17. }]);  
 
$routeProvider

$routeProvider Service is used to configure the routes or the URLs for your Application. In order to configure routes, $routeProvide is injected in config function of an Angular module. You also need to add Angular-route script file after AngularJS and dependency of ngRoute into an Angular module, as shown below.

Syntax
  1. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>//angularJS file    
  2. <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular-route.js"></script>//angular-route file    
  3. <script src="your script file"></script>    
  4.   
  5. angular.module('myApp'['ngRoute']).config(function($routeProvider) {    
  6.      
  7.   $routeProvider    
  8.     .when('/someUrl', {    
  9.       templateUrl: 'templateURL(/abc.html)',    
  10.       controller: 'ControllerName'    
  11.       //other properties  
  12.     })  
  13.    .otherwise('/someURL');//tells angular to redirect user to specific URL in case if it does not understand route or url    
  14.   
  15.     
  16. });  
Plunker-$routeProvider Exampe
 
$routeParams

$routeParams Service is used to retrieve the values of the parameters, which are passed in URL's. While configuring a route, you can specify the parameters in the URL segment by using colon followed by a parameter name.

Synatx
  1. angular.module('myApp', ['ngRoute']).config(function($routeProvider) {     
  2.          
  3.   $routeProvider  
  4. //configure route wit parameter        
  5.     .when('/someUrl/:parameterName', {        
  6.       templateUrl: 'templateURL(/abc.html)',        
  7.       controller: 'ControllerName'        
  8.       //other properties      
  9.     })      
  10.    .otherwise('/someURL');//tells angular to redirect user to specific URL in case if it does not understand route or url        
  11.         
  12. })  
  13. .controller('myController'function($scope,$routeParams) {  
  14. //getting value of parameter  
  15. $scopr.value=$routeParams.parameterName;   
  16.   
  17. });  
Plunker-$routeParams Example 

$log

$log service is used for debugging and troubleshooting purpose. 

Synatx 

  1. angular.module('myApp', [])  
  2.   .controller('myController', ['$scope''$log'function($scope, $log) {  
  3.       
  4.     $log.log("log")  
  5.     $log.warn("log warn")  
  6.     $log.info("log info")  
  7.     $log.error("log error")  
  8.     $log.debug("log debug")  
  9.   }]);  

Plunker-$log Example

Custom AngularJS Services

There are five different ways through which you can create custom Services in AngularJS. 
  1. provider()
  2. factory()
  3. service()
  4. value()
  5. constant() 
provider()

This type of Service is created at the configuration phase.The provider function takes two parameters, the name of Service and the function. The function must contain $get property and the value of this proerty is a function, which is used to create a Service.
 
Syantax 
  1. var myApp=angular.module('myApp',[]);    
  2.     
  3. myApp.config(function($provide){    
  4.       
  5.   $provide.provider('serviceName',function(){    
  6.         
  7.     this.$get=function(){    
  8.       return{    

  9.         //do some stuff  

  10.       }    
  11.     };    
  12.         
  13.   });    
  14.       
  15. });    
 $provide Service is used to create injectable Services.
 
 
facory()

The factory function takes two parameters, the name of the Service and the function, which creates and returns Service.
 
Synatx
  1. var myApp=angular.module('myCustomServiceModule', []);    
  2.    
  3. myApp.factory('myService', [function() {      
  4.        
  5.    return {      
  6.      //do some stuff here    
  7.    };      
  8.  }]);     
Plunker- Custom Service Through factory() Example
 
 service()

The method to create Service through Service() function is same as factory() function but the main difference between them is that Angular treats the function, which is passed to the Service() as a constructor and executes it with the new operator. 

Syntax 
  1. var myApp=angular.module('myCustomServiceModule', []);      
  2.      
  3. myApp.service('myService', [function() {        
  4.          
  5.    return {        
  6.      //do some stuff here      
  7.    };        
  8.  }]);   
 
value()

This fucntion is the short version of factory(). The value function can be used in place of factory, if you dont want to inject anything in your Service.

Syntax
  1. var myApp=angular.module('myApp',[]);    
  2.     
  3.     
  4. myApp.value('myCustomService',{    
  5.     
  6. //do some stuff    
  7.     
  8. });    
Plunker- Custom Service Through value() Example 
 
constant()

The constant funcion is used to define constant values for your Application. This function takes two parameters, the name of the Service and an object literal, which represents the Service.
 
Syntax 
  1. var myApp=angular.module('myApp',[]);    
  2.       
  3. myApp.constant('appSettings',{       
  4.   APP_NAME:"Constant Demo App"    
  5. //do other stuff  
  6. });    
 
Summary

In this article, I discussed some of the commonly used built-in AngularJS Services and the methods through which you can create Custom Services in AngularJS.


Similar Articles