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. //$http get method
  4. $http({
  5. method: 'GET',
  6. url: '/someUrl'
  7. //other properties
  8. }).then(function successCallback(response) {
  9. // this callback will be called asynchronously
  10. // when the response is available
  11. }, function errorCallback(response) {
  12. // called asynchronously if an error occurs
  13. // or server returns response with an error status.
  14. });
  15. //$http get shortcut method
  16. $http.get('/someUrl').then(function successCallback(response) {
  17. // this callback will be called asynchronously
  18. // when the response is available
  19. }, function errorCallback(response) {
  20. // called asynchronously if an error occurs
  21. // or server returns response with an error status.
  22. });
  23. }]);
Plunker - AngularJS $http GET,POST,PUT,DELETE functions
$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. var app=angular.module('app',['ngResource']);
  5. app.controller('mycontroller',['$resource',function($resource){
  6. //resource get method
  7. $resource('/someURL').get().$promise.then(function(data){
  8. //do some stuff
  9. },function(response){
  10. //do some stuff
  11. });
  12. }]);
Plunker: AngularJS $resource GET,POST,PUT,DELETE functions
$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. //service create deffered object and return promise
  3. myApp.service('myService',['$q',function($q) {
  4. //create a deffered object
  5. var defferedObject = $q.defer();
  6. //this method calls when work is being performed
  7. defferedObject.notify('notification messages');
  8. //this method calls when something goes wrong
  9. //and errors send back to the client
  10. defferedObject.reject('Error Message');
  11. //this mehod calls when the require
  12. //work has completed successfuly
  13. //and results are returned to client
  14. defferedObject.resolve(data);
  15. //return promise to caller
  16. return defferedObject.promise;
  17. }]);
  18. myApp.controller('myController',['myService',function(myService){

  19. //code receive the promise
  20. //and write callback functions
  21. //these callback functions receive the result from the service
  22. myFunction().then(successCallBack, errorCallBack, notificationCallBack);
  23. function successCallBack(data) {
  24. //do some stuff with data
  25. }
  26. function errorCallBack(error) {
  27. //do some stuff
  28. }
  29. function notificationCallBack(notification) {
  30. //do some stuff
  31. }

  32. }]);
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. // call $anchorScroll()
  9. $anchorScroll();
  10. };
  11. }]);
Plunker-$anchorScroll Example
$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. //put data into cache
  6. $scope.cache.put(key,value);

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

  9. //get cache info
  10. $scope.cache.info();
  11. }]);
Plunker-$cacheFactory Example
$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. //full date format
  4. $scope.myFormat=$locale.DATETIME_FORMATS.fullDate;

  5. //short date format
  6. $scope.myFormat=$locale.DATETIME_FORMATS.fullDate;
  7. }]);
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. $timeout(function() {
  4. //do some stuff
  5. }, 5000);
  6. }]);
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. var myApp=angular.module('myApp', ['ngCookies'])
  5. .controller('cookiesController', ['$cookies', function($cookies) {
  6. // Retrieving a cookie
  7. var myCookie = $cookies.get('myCookieName');
  8. // Setting a cookie
  9. $cookies.put('myCookieName', 'cookie Value');
  10. //Removing a cookie
  11. $cookies.remove('myCookieName');
  12. }]);
Plunker-$cookies Example
$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. angular.module('myApp', ['ngRoute']).config(function($routeProvider) {
  5. $routeProvider
  6. .when('/someUrl', {
  7. templateUrl: 'templateURL(/abc.html)',
  8. controller: 'ControllerName'
  9. //other properties
  10. })
  11. .otherwise('/someURL');//tells angular to redirect user to specific URL in case if it does not understand route or url
  12. });
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. $routeProvider
  3. //configure route wit parameter
  4. .when('/someUrl/:parameterName', {
  5. templateUrl: 'templateURL(/abc.html)',
  6. controller: 'ControllerName'
  7. //other properties
  8. })
  9. .otherwise('/someURL');//tells angular to redirect user to specific URL in case if it does not understand route or url
  10. })
  11. .controller('myController', function($scope,$routeParams) {
  12. //getting value of parameter
  13. $scopr.value=$routeParams.parameterName;
  14. });
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. $log.log("log")
  4. $log.warn("log warn")
  5. $log.info("log info")
  6. $log.error("log error")
  7. $log.debug("log debug")
  8. }]);

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. myApp.config(function($provide){
  3. $provide.provider('serviceName',function(){
  4. this.$get=function(){
  5. return{

  6. //do some stuff

  7. }
  8. };
  9. });
  10. });
$provide Service is used to create injectable Services.
Plunker- Custom angularJS service through Provider()
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. myApp.factory('myService', [function() {
  3. return {
  4. //do some stuff here
  5. };
  6. }]);
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. myApp.service('myService', [function() {
  3. return {
  4. //do some stuff here
  5. };
  6. }]);
Plunker-Custom Service Through service() Example
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. myApp.value('myCustomService',{
  3. //do some stuff
  4. });
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. myApp.constant('appSettings',{
  3. APP_NAME:"Constant Demo App"
  4. //do other stuff
  5. });
Plunker-Custom Service Through constant() Example
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.