AngularJS Services

AngularJS supports the concepts of "Separation of Concerns" using services. Services provide us a method to keep data across the lifetime of the Angular application. Angular services are substitutable objects that are wired together using dependency injection. We can use services to organize and share code across our app. Services are JavaScript functions that are responsible for specific tasks only. Services provide us a method to communicate data across the controllers in a consistent way. It provides individual entities that are maintainable and testable. Services are singleton objects and they get instantiated only once per application; controllers and filters only call them on an as-required basis. Services are singleton objects;  that means each component dependent on a service gets a reference to the single instance generated by the service factory.

AngularJS provide many inbuilt services like $animate, $http, $route, $window, $location, $compile, $controller, etc.

Let us take some example of inbuilt services.

$http:

AngularJS provides $http control which works as a service to read data from the server. The $http is a core AngularJS service that is used to communicate with the remote HTTP service via browser’s XMLHttpRequest object or via JSONP.

Example:

  1. <html>  
  2.   
  3. <head>  
  4.     <title>Angular JS Includes</title>  
  5.     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">  
  6.         </script>  
  7.         <script src="angular.min.js">  
  8.             </script>  
  9. </head>  
  10.   
  11. <body>  
  12.     <h2>AngularJS Ajax Demo</h2>  
  13.     <div ng-app="app" ng-controller="Employee"><span>{{Message}}</span><br/><span>{{Status}}</span><br/>  
  14.         <br/></div>  
  15.         <script>  
  16.             var obj = angular.module('app', []);  
  17.             obj.controller('Employee', function($scope, $http)  
  18.             {  
  19.                 $http({  
  20.                     method: 'GET',  
  21.                     url: 'index.html'  
  22.                 }).then(functionsuccessCallback(response)   
  23.                 {  
  24.                     $scope.Message = response.data;  
  25.                     $scope.Status = response.status;  
  26.   
  27.                 }, function errorCallback(response)  
  28.                 {  
  29.                     alert("UnsuccessFull call!");  
  30.                 });  
  31.             });  
  32.         </script>  
  33. </body>  
  34.   
  35. </html>  
Index.HTML: This is $Ajax Example.

Output:

output
$window:

$window refers to the browser’s window object. In Angular we always refer window through the $ window service, so it may be overriddenor  removed for testing.

Example:
  1. <html>  
  2.   
  3. <head>  
  4.     <title>Angular JS Includes</title>  
  5.     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">  
  6.         </script>  
  7.         <scrip tsrc="angular.min.js">  
  8.             </script>  
  9. </head>  
  10.   
  11. <body ng-app="app">  
  12.     <h2>AngularJS $Window Example</h2>  
  13.     <div ng-controller="mycontroller">  
  14.         <input type="text" ng-model="message" aria-label="greeting" />  
  15.         <button ng-click="doGreeting(message)">ALERT BOX</button>  
  16.             </div>  
  17.             <script>  
  18.                 var obj = angular.module('app', []);  
  19.                 obj.controller('mycontroller', ['$scope''$window', function($scope, $window) {  
  20.                     $scope.message = 'I am $window Service!';  
  21.                     $scope.doGreeting = function(message)  
  22.                     {  
  23.                         $window.alert(message);  
  24.                     };  
  25.                 }]);  
  26.             </script>  
  27.             </body>  
  28.   
  29. </html>  
Output:

output

$document:

The $document is a jQuery wrapper for the browser’s window.object method.

Example:
  1. <html>  
  2.   
  3. <head>  
  4.     <title>Angular JS Example</title>  
  5.     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">  
  6.         </script>  
  7.         <script src="angular.min.js">  
  8.             </script>  
  9. </head>  
  10.   
  11. <body ng-app="app">  
  12.     <h2>AngularJS $document Example</h2>  
  13.     <div ng-controller="myController">  
  14.         <span id="pan">Pankaj Kumar Choudhary</span>  
  15.             <p>  
  16.                 <bng-bind="title">  
  17.                     </b>  
  18.             </p>  
  19.             <p>  
  20.                 <bng-bind="windowTitle">  
  21.                     </b>  
  22.             </p>  
  23.             </div>  
  24.             <script>  
  25.                 var obj = angular.module('app', []);  
  26.                 obj.controller('myController', ['$scope''$document', function($scope, $document)  
  27.                 {  
  28.                     $scope.title = $document[0].title;  
  29.                     $scope.windowTitle = angular.element(window.document)[0].title;  
  30.                 }]);  
  31.             </script>  
  32.             </body>  
  33.   
  34. </html>  
Output:

output

Way to define User Services:

Here are the ways to define the services.
  1. factory
  2. service
  3. provider
  4. value

Factory:

Usin the factory method, we first define a factory and then assign a method to it. A factory is a simple function which allows us to add some logic before creating the object and at last we return this object. It is a collection of function similar to a class. It can be used in multiple controllers with constructor function.

  1. <html>  
  2.   
  3. <head>  
  4.     <title>Angular JS Example</title>  
  5.     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">  
  6.         </script>  
  7.         <script src="angular.min.js">  
  8.             </script>  
  9. </head>  
  10.   
  11. <body>  
  12.     <h2>AngularJS Service Example</h2>  
  13.     <div ng-app="mainApp" ng-controller="CalcController">  
  14.         <p>Enter First number:  
  15.             <inputtype="number" ng-model="number1" />  
  16.         </p>  
  17.         <p>Enter Second number:  
  18.             <inputtype="number" ng-model="number2" />  
  19.         </p>  
  20.         <button ng-click="multiply()">Multiply</button>  
  21.             <p>Result: {{result}}</p>  
  22.             </div>  
  23.             <script>  
  24.                 var mainApp = angular.module("mainApp", []);  
  25.   
  26.                 mainApp.factory('MathService', function()  
  27.                 {  
  28.                     var factory = {};  
  29.   
  30.                     factory.multiply = function(a, b)  
  31.                     {  
  32.                         return a * b  
  33.                     }  
  34.                     return factory;  
  35.                 });  
  36.                 mainApp.controller('CalcController', function($scope, MathService)  
  37.                 {  
  38.                     $scope.multiply = function()  
  39.                     {  
  40.                         $scope.result = MathService.multiply($scope.number1, $scope.number2);  
  41.                     }  
  42.                 });  
  43.             </script>  
  44. </body>  
  45.   
  46. </html>  
Output:

output
Service:

Using service method we define a service and after that assign a method to this service. A service is a constructor function which creates the object using  a new keyword and we can add function and property to this object using this keyword.
  1. <html>  
  2.   
  3. <head>  
  4.     <title>Angular JS Example</title>  
  5.     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">  
  6.         </script>  
  7.         <script src="angular.min.js">  
  8.             </script>  
  9. </head>  
  10.   
  11. <body>  
  12.     <h2>AngularJS Service Example</h2>  
  13.     <div ng-app="mainApp" ng-controller="CalcController">  
  14.         <p>Enter First number:  
  15.             <input type="number" ng-model="number1" />  
  16.         </p>  
  17.         <p>Enter Second number:  
  18.             <input type="number" ng-model="number2" />  
  19.         </p>  
  20.         <button ng-click="multiply()">Multiply</button>  
  21.             <p>Result: {{result}}</p>  
  22.             </div>  
  23.             <script>  
  24.                 var mainApp = angular.module("mainApp", []);  
  25.                 mainApp.service('MathService', function()  
  26.                  {  
  27.                     this.multiply = function(a, b)  
  28.                     {  
  29.                         return a * b  
  30.                     }  
  31.                 });  
  32.                 mainApp.controller('CalcController', function($scope, MathService)  
  33.                 {  
  34.                     $scope.multiply = function()  
  35.                     {  
  36.                         $scope.result = MathService.multiply($scope.number1, $scope.number2);  
  37.                     }  
  38.                 });  
  39.             </script>  
  40. </body>  
  41.   
  42. </html>  
Output:

output
We can also inject an already available service to it. In the below example we insert a multiply_data method into a service that already exists in factory service.

Example:
  1. <html>  
  2.   
  3. <head>  
  4.     <title>Angular JS Example</title>  
  5.     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">  
  6.         </script>  
  7.         <script src="angular.min.js">  
  8.             </script>  
  9. </head>  
  10.   
  11. <body>  
  12.     <h2>AngularJS Service Example</h2>  
  13.     <div ng-app="mainApp" ng-controller="CalcController">  
  14.         <p>Enter First number:  
  15.             <input type="number" ng-model="number1" />  
  16.         </p>  
  17.         <p>Enter Second number:  
  18.             <input type="number" ng-model="number2" />  
  19.         </p>  
  20.         <button ng-click="multiply()">Multiply</button>  
  21.             <p>Result: {{result}}</p>  
  22.             </div>  
  23.             <script>  
  24.                 varmainApp = angular.module("mainApp", []);  
  25.   
  26.                 mainApp.factory('MathService_Factory', function()  
  27.                  {  
  28.                     var factory = {};  
  29.   
  30.                     factory.multiply_data = function(a, b)  
  31.                     {  
  32.                         return a * b  
  33.                     }  
  34.                     return factory;  
  35.                 });  
  36.   
  37.                 mainApp.service('MathService', function(MathService_Factory)  
  38.                 {  
  39.                     this.multiply = function(a, b)  
  40.                     {  
  41.                         returnMathService_Factory.multiply_data(a, b);  
  42.                     }  
  43.                 });  
  44.                 mainApp.controller('CalcController', function($scope, MathService)  
  45.                 {  
  46.                     $scope.multiply = function()  
  47.                     {  
  48.                         $scope.result = MathService.multiply($scope.number1, $scope.number2);  
  49.                     }  
  50.                 });  
  51.             </script>  
  52. </body>  
  53.   
  54. </html>  
Output:

output
Provider:

A provider is used to create a configurable service object and value returned using the $get() function. We should use the provider method when we need to provide module-wise configuration for your service object before making it available.

Example:
  1. <html>  
  2.   
  3. <head>  
  4.     <title>Angular JS Example</title>  
  5.     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">  
  6.         </script>  
  7.         <script src="angular.min.js">  
  8.             </script>  
  9. </head>  
  10.   
  11. <body>  
  12.     <h2>AngularJS Service Example</h2>  
  13.     <div ng-app="mainApp" ng-controller="CalcController">  
  14.         <p>Multiply of 79 and 13 is </p>  
  15.         <p>Result: {{result}}</p>  
  16.         </div>  
  17.         <script>  
  18.             varmainApp = angular.module("mainApp", []);  
  19.   
  20.             mainApp.provider('configurable', function()  
  21.             {  
  22.                 var multi = 0;  
  23.                 this.multiply = function(a, b)  
  24.                 {  
  25.                     multi = a * b;  
  26.                 };  
  27.                 this.$get = function()  
  28.                 {  
  29.                     return  
  30.                     {  
  31.                         data: multi  
  32.                     };  
  33.                 };  
  34.             });  
  35.             mainApp.config(function(configurableProvider)  
  36.             {  
  37.                 configurableProvider.multiply(79, 13);  
  38.             });  
  39.             mainApp.controller('CalcController', function($scope, configurable)   
  40.             {  
  41.                 $scope.result = configurable.data;  
  42.             });  
  43.         </script>  
  44. </body>  
  45.   
  46. </html>  
Output:

output
Value:

A value service is used to provide a value. It does exactly what we would expect it to and plays a key part in designing flexible, modular Angular applications.

Example:
  1. <html>  
  2.   
  3. <head>  
  4.     <title>Angular JS Example</title>  
  5.     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">  
  6.         </script>  
  7.         <script src="angular.min.js">  
  8.             </script>  
  9. </head>  
  10.   
  11. <body>  
  12.     <h2>AngularJS Service Example</h2>  
  13.     <divng-app="mainApp" ng-controller="CalcController">  
  14.         <p>{{message}}</p>  
  15.         <p>Result: {{result}}</p>  
  16.         </div>  
  17.         <script>  
  18.             varmainApp = angular.module("mainApp", []);  
  19.   
  20.             mainApp.value("valueId", 79 * 13);  
  21.             mainApp.value("message""Multiply of 79 and 13 is")  
  22.             mainApp.controller('CalcController', function($scope, valueId, message) {  
  23.                 $scope.result = valueId;  
  24.                 $scope.message = message;  
  25.             });  
  26.         </script>  
  27. </body>  
  28.   
  29. </html>  
Output:

output
Example:
  1. <html>  
  2.   
  3. <head>  
  4.     <title>Angular JS Example</title>  
  5.     <scriptsrc="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js">  
  6.         </script>  
  7.         <scriptsrc="angular.min.js">  
  8.             </script>  
  9. </head>  
  10.   
  11. <body>  
  12.     <h2>AngularJS Service Example</h2>  
  13.     <divng-app="mainApp" ng-controller="CalcController">  
  14.         <p>Enter First number:  
  15.             <inputtype="number" ng-model="number1" />  
  16.         </p>  
  17.         <p>Enter Second number:  
  18.             <inputtype="number" ng-model="number2" />  
  19.         </p>  
  20.         <buttonng-click="Result()">Result</button>  
  21.             <p>Multiplication: {{multiply}}</p>  
  22.             <p>Addition: {{addition}}</p>  
  23.             <p>Substraction: {{substraction}}</p>  
  24.             <p>Divison: {{divison}}</p>  
  25.   
  26.             </div>  
  27.             <script>  
  28.                 varmainApp = angular.module("mainApp", []);  
  29.                 //Factory  
  30.                 mainApp.factory('MathService', function() {  
  31.                     var factory = {};  
  32.   
  33.                     factory.multiply = function(a, b) {  
  34.                         return a * b  
  35.                     }  
  36.                     return factory;  
  37.                 });  
  38.                 //Service  
  39.                 mainApp.service('addition', function() {  
  40.                     this.add = function(a, b) {  
  41.                         return a + b  
  42.                     }  
  43.                 });  
  44.   
  45.                 //Provider  
  46.                 mainApp.provider('configurable', function() {  
  47.                     var sub = 0;  
  48.                     this.substraction = function(a, b) {  
  49.                         sub = a * b;  
  50.                     };  
  51.                     this.$get = function() {  
  52.                         return {  
  53.                             data: sub  
  54.                         };  
  55.                     };  
  56.                 });  
  57.                 mainApp.config(function(configurableProvider)  
  58.                 {  
  59.                     configurableProvider.substraction(79, 13);  
  60.                 });  
  61.   
  62.   
  63.                 //Value  
  64.                 mainApp.value("valueId", 79 / 13);  
  65.                 //Controller  
  66.                 mainApp.controller('CalcController', function($scope, MathService, addition, configurable, valueId)   
  67.                 {  
  68.                     $scope.Result = function()  
  69.                     {  
  70.                         $scope.multiply = MathService.multiply($scope.number1, $scope.number2);  
  71.                         $scope.addition = addition.add($scope.number1, $scope.number2);  
  72.                         $scope.substraction = configurable.data;  
  73.                         $scope.divison = valueId;  
  74.                     }  
  75.                 });  
  76.             </script>  
  77.   
  78. </body>  
  79.   
  80. </html>  
Output:

output
In the above example we used factory, service, value and provider services.

Read more articles on AngularJS:

Up Next
    Ebook Download
    View all
    Learn
    View all