Services in AngularJS For Beginners

Services are one of the important concepts in AngularJS. In general Services are functions that are responsible for specific tasks in an application. AngularJS services are designed based on two principles.

  1. Lazily instantiated: Angular only instantiates a service when an application component depends on it using dependency injection for making Angular the codes robust and less error prone.
  2. Singletons: Each component is dependent on a service that gets a reference to the single instance generated by the service factory.

AngularJS supports the concepts of "Separation of Concerns" using a services-oriented architecture and it is at the heart when designing an AngularJS application. Controllers, filters or directives can call them on the basis of requirements. The controller must be responsible for binding model data to views using $scope. It does not contain logic to fetch the data or manipulating it.

Services provide a method to share data across the lifetime of the AngularJS application. It provides a method to communicate data across the controllers in a consistent way. This is a singleton object and it is instantiated only once per application. It is used to organize and share data and functions across the application.

Thus a service is a stateless object that contains some useful functions. These functions can be called from anywhere; Controllers, Directive, Filters and so on. Thus we can divide our application into logical units. The business logic or logic to call HTTP URL to fetch data from the server can be put within a service object.

Putting business and other logic within services has many advantages. First, it fulfils the principle of separation of concerns or segregation of duties. Each component is responsible for its own work making application code more manageable and more testable. Thus we can quickly write tests for our services making them robust and less error-prone.

AngularJS provides many builtin services, for example, $http, $route, $window, $location and so on. Each service is responsible for a specific task, for example, $http is used to make an Ajax call to get the server data. $route defines the routing information and so on. Builtin services are always prefixed with the $ symbol.

AngularJS internal services

AngularJS internally provides many services that we can use in our application. $http is one example. There are other useful services, such as $route, $window, $location and so on. Some of the commonly used services in any AngularJS applications are listed below.

  • $window: Provide a reference to a DOM object.
  • $Location: Provides reference to the browser location.
  • $timeout: Provides a reference to window.settimeout function.
  • $Log: Used for logging.
  • $sanitize: Used to avoid script injections and display raw HTML in page.
  • $Rootscope: Used for scope hierarchy manipulation.
  • $Route: Used to display browser based path in browser URL.
  • $Filter: Used for providing filter access.
  • $resource: Used to work with Restful API.
  • $document: Used to access the window. Document object.
  • $exceptionHandler: Used for handling exceptions.
  • $q: Provides a promise object.

Here, the question arises in our mind that we had window, window.Location, document and timeout in the DOM in JavaScript, so why does $window, $location, $document, $timeout in terms of a services. The reason behind is to support dependency injection and to more easily test using a mocked version of $window, $location, $document and $timeout services.

So what is the mocked version and what is mocking?

Mocking is primarily used in unit testing. An object under test may have dependencies on other (complex) objects. To isolate the behaviour of the object you want to test you replace the other objects by mocks that simulate the behaviour of the real objects. This is useful if the real objects are impractical to incorporate into the unit test.

Let's understand some of the AngularJS internal services.

$window Service

Example-1

  1. <!DOCTYPE html>  
  2. <html ng-app="WindowsServiceapp">  
  3.     <head>  
  4.         <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>  
  5.         <script>  
  6. angular.module("WindowsServiceapp", [])  
  7. .controller("WindowsServicectrl", function ($scope, $window)  
  8. {  
  9. $scope.dissplayAlert = function (msg)   
  10. {  
  11. $window.open("http://www.google.com", "test", 'height=200,width=550');  
  12. $window.document.write("Testing....");  
  13. $window.alert(msg);  
  14. }  
  15. });  
  16. </script>  
  17.     </head>  
  18.     <body>  
  19.         <div ng-app="WindowsServiceapp">  
  20.             <div ng-controller="WindowsServicectrl">  
  21.                 <div>  
  22.                     <button name="btn" ng-click="dissplayAlert('clicked')">click me </button>  
  23.                 </div>  
  24.             </div>  
  25.         </div>  
  26.     </body>  
  27. </html>  
Output



Here in the “WindowsServicectrl” $window service is injected and showing an alert and opening pop-up window in the preceding example. Note that $windows is not the same window object. To keep the window object an injectable component for manipulation of AngularJS that has created a wrapper on the window object.

$http Services

Let us understand the $http service that makes a service call for server communication. Now we will see a simple Http service that is used to fetch the data from a SQL Server database.

We have an employee table that contains some employee information as in the following:



We have a web API that is a source of a data layer that connects to a database and we need to call it using Angular code.

Example 2
  1. public class EmployeeAPIController: ApiController  
  2. {  
  3.     private EmployeeEntities db = new EmployeeEntities();  
  4.     public IEnumerable < Employee > GetEmployees()  
  5.     {  
  6.         return db.Employees.AsEnumerable();  
  7.     }  
  8. }  
Service
  1. app.service('EmployeeService', function ($http)   
  2. {  
  3. this.getAllEmployee = function ()  
  4.  {  
  5. return $http.get("/api/EmployeeAPI");// Calling the web api here  
  6. }  
  7. });  
Controller
  1. app.controller('EmployeeController', function($scope, EmployeeService)  
  2. {  
  3.     GetAllRecords();  
  4.     function GetAllRecords()   
  5.     {  
  6.         var promiseGet = EmployeeService.getAllEmployee();  
  7.         promiseGet.then(function(pl)   
  8.         {  
  9.             $scope.Employees = pl.data  
  10.         },  
  11.         function(errorPl)   
  12.         {  
  13.             $log.error('Some Error in Getting Records.', errorPl);  
  14.         });  
  15.     }  
  16. });  
Module
  1. var app;  
  2. (function ()   
  3. {  
  4. app = angular.module("EmployeeModule", []);  
  5. })();  
HTML Page
  1. <html ng-app="EmployeeModule">  
  2.     <head>  
  3.         <style type="text/css">  
  4. table.table-style  
  5. {  
  6. font-family: verdana, arial, sans-serif;  
  7. font-size: 11px;  
  8. color: #333333;  
  9. border-width: 1px;  
  10. border-color: #3A3A3A;  
  11. border-collapse: collapse;  
  12. border: 2px solid gray;  
  13. background-color: #f5f5f5;  
  14. }  
  15. table.table-style th  
  16. {  
  17. border-width: 1px;  
  18. padding: 8px;  
  19. border-style: solid;  
  20. border-color: #FFA6A6;  
  21. background-color: #D56A6A;  
  22. color: #ffffff;  
  23. }  
  24. table.table-style tr:hover td  
  25. {  
  26. cursor: pointer;  
  27. }  
  28. table.table-style tr:nth-child(even) td  
  29. {  
  30. background-color: #F7CFCF;  
  31. }  
  32. table.table-style td  
  33. {  
  34. border-width: 1px;  
  35. padding: 8px;  
  36. border-style: solid;  
  37. border-color: #FFA6A6;  
  38. background-color: #ffffff;  
  39. }  
  40. </style>  
  41.     </head>  
  42.     <body data-ng-controller="EmployeeController">  
  43.         <table class="table-style">  
  44.             <tr>  
  45.                 <th>ID</th>  
  46.                 <th>Name</th>  
  47.                 <th>Role</th>  
  48.                 <th>Birth Day</th>  
  49.                 <th>Gender</th>  
  50.                 <th>HireDate</th>  
  51.             </tr>  
  52.             <tbody data-ng-repeat="emp in Employees">  
  53.                 <tr>  
  54.                     <td>  
  55.                         <span>{{emp.EmployeeID}}</span>  
  56.                     </td>  
  57.                     <td>  
  58.                         <span>{{emp.Name}}</span>  
  59.                     </td>  
  60.                     <td>  
  61.                         <span>{{emp.Title}}</span>  
  62.                     </td>  
  63.                     <td>  
  64.                         <span>{{emp.BirthDate}}</span>  
  65.                     </td>  
  66.                     <td>  
  67.                         <span>{{emp.Gender}}</span>  
  68.                     </td>  
  69.                     <td>  
  70.                         <span>{{emp.HireDate}}</span>  
  71.                     </td>  
  72.                 </tr>  
  73.             </tbody>  
  74.         </table>  
  75.     </body>  
  76. </html>  
  77. <script src="~/Scripts/angular.js"></script>  
  78. <script src="~/Scripts/EmployeeScripts/Module.js"></script>  
  79. <script src="~/Scripts/EmployeeScripts/Service.js"></script>  
  80. <script src="~/Scripts/EmployeeScripts/Controller.js"></script>
Output


User Defined Services

Let us create some of the services that we need to write based on our requirements. We will create a calculation web page that does Addition, Subtraction, Multiplication and Division. We will create a service called "CalculatorService" and call this calculator service in the controller. From the controller the service results are assigned to the Scope object and finally shown to the UI.

Example 3
  1. <!DOCTYPE html>  
  2. <html ng-app="app">  
  3.     <head>  
  4.         <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js">  
  5.             <script>  
  6. var CalculatorService = angular.module('CalculatorService', [])  
  7. .service('Calculator', function ()   
  8. {  
  9. this.Add = function (a, b) { return Number(a) + Number(b) };  
  10. this.Sub = function (a, b) { return Number(a) - Number(b) };  
  11. this.Mul = function (a, b) { return Number(a) * Number(b) };  
  12. this.Div = function (a, b) { return Number(a) / Number(b) };  
  13. });  
  14. var myApp = angular.module('app', ['CalculatorService']);  
  15. myApp.controller('CalculatorController', function ($scope, Calculator) {  
  16. $scope.doAdd = function ()   
  17. {  
  18. $scope.result = Calculator.Add($scope.a, $scope.b);  
  19. }  
  20. $scope.doSub = function ()  
  21. {  
  22. $scope.result = Calculator.Sub($scope.a, $scope.b);  
  23. }  
  24. $scope.doMul = function ()   
  25. {  
  26. $scope.result = Calculator.Mul($scope.a, $scope.b);  
  27. }  
  28. $scope.doDiv = function ()  
  29. {  
  30. $scope.result = Calculator.Div($scope.a, $scope.b);  
  31. }  
  32. });  
  33. </script>  
  34.         </head>  
  35.         <body>  
  36.             <div ng-app="app">  
  37.                 <div ng-controller="CalculatorController">  
  38.                     <div>  
  39.                         <table style="width: 600px; border: 2px solid gray; background-color: #f5f5f5;">  
  40.                             <tr>  
  41.                                 <td>  
  42.                                     <strong></strong>  
  43.                                 </td>  
  44.                                 <td>  
  45.                                     <strong>Calculator Service</strong>  
  46.                                 </td>  
  47.                                 <td>  
  48.                                     <strong></strong>  
  49.                                 </td>  
  50.                                 <td>  
  51.                                     <strong></strong>  
  52.                                 </td>  
  53.                                 <td>  
  54.                                     <strong></strong>  
  55.                                 </td>  
  56.                             </tr>  
  57.                             <tr>  
  58.                                 <td>  
  59.                                     <strong>Enter First Number:</strong>  
  60.                                 </td>  
  61.                                 <td>  
  62.                                     <input type="text" ng-model="a" />  
  63.                                 </td>  
  64.                                 <td></td>  
  65.                                 <td></td>  
  66.                                 <td></td>  
  67.                             </tr>  
  68.                             <tr>  
  69.                                 <td>  
  70.                                     <strong>Enter Second Number:</strong>  
  71.                                 </td>  
  72.                                 <td>  
  73.                                     <input type="text" ng-model="b" />  
  74.                                 </td>  
  75.                                 <td></td>  
  76.                                 <td></td>  
  77.                                 <td></td>  
  78.                             </tr>  
  79.                             <br />  
  80.                             <tr>  
  81.                                 <td></td>  
  82.                                 <td>  
  83.                                     <button ng-click="doAdd()">Add</button>  
  84.                                     <button ng-click="doSub()">Subtract</button>  
  85.                                     <button ng-click="doMul()">Multify</button>  
  86.                                     <button ng-click="doDiv()">Divide</button>  
  87.                                 </td>  
  88.                                 <td></td>  
  89.                                 <td></td>  
  90.                                 <td></td>  
  91.                             </tr>  
  92.                             <tr>  
  93.                                 <td>  
  94.                                     <strong>The Result from Calculation Service is: </strong>  
  95.                                     <b>{{result}}</b>  
  96.                                 </td>  
  97.                             </tr>  
  98.                         </table>  
  99.                     </div>  
  100.                 </div>  
  101.             </div>  
  102.         </body>  
  103.     </html>  
Output



So we created a service and saw the result of the service.

In general, a service can be created in many ways, they are:
  • Service
  • Factory
  • Provider
  • Value
  • Constant

Factory: A factory is a simple function that allows you to add some logic before creating the object. It returns the created object.

Example of defining a factory

  1. //define a factory using factory ()  
  2. function app.factory('MyFactory', function()  
  3. {  
  4.     var serviceObj = {};  
  5.     serviceObj.fun1 = function()  
  6.     {  
  7.         //TO DO the logic part goes here  
  8.     };  
  9.     serviceObj.fun2 = function()  
  10.     {  
  11.         //TO DO the logic part goes here  
  12.     };  
  13.     return serviceObj;  
  14. });  
When to use Factory: It is just a collection of functions like a class. Hence, it can be instantiated in different controllers when you are using it with a constructor function.

Service: A service is a constructor function that creates the object using the new keyword. You can add properties and functions to a service object using this keyword. Unlike factory, it doesn't return anything.

Example of define a service using service()
  1. function app.service('MyService', function()   
  2. {  
  3.     this.func1 = function()  
  4.     {  
  5.         //TO DO the logic part goes here  
  6.     };  
  7.     this.fun2 = function()  
  8.     {  
  9.         //TO DO the logic part goes here  
  10.     };  
  11. });  
When to use Service: It is a singleton object. Use it when you need to share a single object across the application. For example, authenticated user details, share-able data and so on.

Provider: A provider is used to create a configurable service object. It returns a value using the $get() function.

Example of defining define a provider
  1. function app.provider('configurable', function()  
  2. {  
  3.     var privateName = '';  
  4.     this.setName = function(newName)  
  5.     {  
  6.         privateName = newName;  
  7.     };  
  8.     this.$get = function()  
  9.     {  
  10.         return   
  11.         {  
  12.             name: privateName  
  13.         };  
  14.     };  
  15. });  
  16. //configuring provider using config()  
  17. function app.config(function(configurableService)  
  18. {  
  19.     configurableService.setName('Angular Js Provider sample');  
  20. });  
When to use provider: When you need to provide a module-wise configuration for your service object before making it available. You should use the Provider recipe only when you want to expose an API for application-wide configuration that must be made before the application starts.

Value: Values are simple objects that are used to share data globally within a module. A value can be a number, string, date-time, array or object. You can also register a function as a value.

Example 4
  1. <!DOCTYPE html>  
  2. <html ng-app="app">  
  3.     <head>  
  4.         <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>  
  5.         <script>  
  6. var app = angular.module('app', []);  
  7. app.value('Data',  
  8. {message:"I am data from a service"}  
  9. )  
  10. app.controller('FirstCtrl', function($scope, Data)   
  11. {  
  12. $scope.data = Data;  
  13. console.log($scope.data)  
  14. });  
  15. </script>  
  16.     </head>  
  17.     <body >  
  18.         <div ng-controller="FirstCtrl">  
  19.             <input type="text" ng-model="data.message">  
  20.                 <br>data.message={{data.message}}  
  21.         </div>  
  22.     </body>  
  23. </html> 
Output



Constant: A constant is like a value. The difference between a value and a constant service is that a constant service can be injected into a module configuration function, in other words config() or run() but a value service cannot be.

Example 5
  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>  
  5.         <meta charset="utf-8">  
  6.             <title>Validated constants</title>  
  7.             <script>  
  8.   
  9. angular.module('MyApp.Constants', []);  
  10. angular.module('MyApp', ['MyApp.Constants'])  
  11. .run(function ($rootScope, username)   
  12. {  
  13. // start using constants module  
  14. $rootScope.username = username;  
  15. });  
  16. </script>  
  17.         </head>  
  18.         <body ng-app="MyApp">  
  19.             <script>  
  20. // inject actual values when needed, the module already exists  
  21. angular.module('MyApp.Constants').constant('username', 'World');  
  22. </script>  
  23.             <p>Hello, {{ username }}</p>  
  24.         </body>  
  25. </html>  
Output: Hello, World

We could not provide any default values for the constants. We could not validate the constants passed to the module until much later, or by making a dummy.run call just to validate them.

Let us see a sample wherein we will write 3 ways to return the service by factory, provider and services in three ways as stated earlier.

Example 6
  1. <!DOCTYPE html>  
  2. <html ng-app="myApp">  
  3.     <head>  
  4.         <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>  
  5.         <script>  
  6. var myApp = angular.module('myApp', []);  
  7. //Creating as service  
  8. myApp.service('helloWorldFromService', function ()  
  9. {  
  10. this.sayHello = function ()  
  11. {  
  12. return "Hello, World!:I am From Service"  
  13. };  
  14. });  
  15. //Creating as factory as a return function  
  16. myApp.factory('helloWorldFromFactory', function ()   
  17. {  
  18. return   
  19. {  
  20. sayHello: function ()   
  21. {  
  22. return "Hello, World!:I am From Factory"  
  23. }  
  24. };  
  25. });  
  26. //Creating as provider as a getter  
  27. myApp.provider('helloWorld', function ()  
  28. {  
  29. this.name = 'Default';  
  30. this.$get = function ()   
  31. {  
  32. var name = this.name;  
  33. return   
  34. {  
  35. sayHello: function ()   
  36. {  
  37. return "Hello, " + name + "!:I am From provider"  
  38. }  
  39. }  
  40. };  
  41. this.setName = function (name)   
  42. {  
  43. this.name = name;  
  44. };  
  45. });  
  46. myApp.config(function (helloWorldProvider)   
  47. {  
  48. helloWorldProvider.setName('World');  
  49. });  
  50. myApp.controller('MyCtrl', function ($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {  
  51. $scope.hellos = [  
  52. helloWorld.sayHello(),  
  53. helloWorldFromFactory.sayHello(),  
  54. helloWorldFromService.sayHello()];  
  55. });  
  56. </script>  
  57.     </head>  
  58.     <body ng-app="myApp">  
  59.         <div ng-controller="MyCtrl">  
  60. {{hellos}}  
  61. </div>  
  62.     </body>  
  63. </html>  
Output



Both services and factory providers get the same output but the choice of when to use them is important.

We can call services inside a service too. Consider a scenario in a real application with a service called Authentication services and RoleServices that must be determined based on the Authentication services result. On that scenario we need to call services inside services. Let's see a simple example to demonstrate this. We have a service named MathService and CalculatorService. The Calculator Service needs MathService as a dependent service.

Example 7
  1. <!DOCTYPE html>  
  2. <html ng-app="app">  
  3.     <head>  
  4.         <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>  
  5.         <script type='text/javascript'>  
  6. var app = angular.module('app', []);  
  7. app.service('MathService', function () {  
  8. this.multiply = function (a, b) { return a * b };  
  9. });  
  10. app.service('CalculatorService', function (MathService) {  
  11. this.square = function (a) { return MathService.multiply(a, a); };  
  12. this.cube = function (a) { return MathService.multiply(a, MathService.multiply(a, a)); };  
  13. });  
  14. app.controller('CalculatorController', function ($scope, CalculatorService) {  
  15. $scope.doSquare = function () {  
  16. $scope.answer = CalculatorService.square($scope.number);  
  17. }  
  18. $scope.doCube = function () {  
  19. $scope.answer = CalculatorService.cube($scope.number);  
  20. }  
  21. });  
  22. </script>  
  23.     </head>  
  24.     <body>  
  25.         <div ng-app="app">  
  26.             <div ng-controller="CalculatorController">  
  27.                 Enter a number  
  28.                 <input type="number" ng-model="number" />  
  29.                 <button ng-click="doSquare()">X  
  30.                     <sup>2</sup>  
  31.                 </button>  
  32.                 <button ng-click="doCube()">X  
  33.                     <sup>3</sup>  
  34.                 </button>  
  35.                 <div>The Answer is: {{answer}}</div>  
  36.             </div>  
  37.         </div>  
  38.     </body>  
  39. </html>  
Output



This is all about the basics of services in AngularJS. In the next article I will return with more on services. I hope you now have a basic knowledge of services.

Thanks for reading.

X

Build smarter apps with Machine Learning, Bots, Cognitive Services - Start free.

Start Learning Now