Understanding Services In AngularJS

Introduction

Service in AngularJS is a function or an object that can be used to share data and the behaviour across the application (controller, directives, filters, other services etc.) or we can say services in AngularJS are objects that are wired together using DI (dependency injection) and it can be used to share and organize code across the application.

We can consider services as a singleton object because their is only one instance of a specific service available during the lifetime of the Angular application. They are instantiated by using the "$injector". Generally they provide an interface to create logical grouping of method together related to a specific function.

There are the following two characteristics of AngularJS services:

  • Lazy instantiated: AngularJS application instantiates a service component when any application component depends on it.

  • Singletons: All components, those dependent on a service get a reference to the single instance generated by the service factory.

Structure of Idle AngularJS Application

Separation of concern is the main objective of AngularJS application. Our controller must be responsible for databinding with the view using $scope and contains some business logic. Controller does not contain any logic to fetch the data. AngularJS services manage the data fetching. In AngularJS application, each component has their own responsibilities so that each component can become more testable.

AngularJS Service

AngularJS internal services

AngularJS internally provides many services that can be used in our application. All the AngularJS internal service start with $ (dollar) sign. $http, $route, $location, $window, $q, etc are useful services provided by AngularJS.

AngularJS custom services

With AngularJS application, we can define our own service and we can use them whenever required. There are many ways to create Services in AngularJS. The following are two very simple ways to create service.

  1. Using service keyword

    Use the "service" keyword is the easiest way to create Service in AngularJS application. In the following code snippet, second parameter is service function in which we define the behaviour of the service. Once we define the service, we can use this service anywhere by injecting this service as dependency.
    1. Defining service without dependency:  
    2.   
    3. var app = angular.module('myapp', []);  
    4.   
    5. app.service('myTestService', function(){  
    6.    // write your service here  
    7.    // define variable and methods   
    8.   
    9. });  
    Defining service with dependency:
    1. var app = angular.module('myapp', []);  
    2.   
    3. app.service('myTestService', ['$http', function($http){  
    4.    // write your service here  
    5.    // define variable and methods   
    6.      
    7. }]);  
  2. Using factory method

    Instead of defining the service directly using the "Service" keyword of the Angular module we can also use the Factory method and services will be created on request when defined by a factory function. The purpose of the service factory is to generate the single object that can be used for the rest of the application.

    Defining service without dependency:
    1. var app = angular.module('myapp', []);  
    2.   
    3. app. factory ('myTestService', function(){  
    4.    // write your service here  
    5.    // define variable and methods   
    6.   
    7. });  
    Defining service with dependency.
    1. var app = angular.module('myapp', []);  
    2.   
    3. app.factory('myTestService', ['$http', function($http){  
    4.    // write your service here  
    5.    // define variable and methods   
    6.   
    7. }]);  

End to End example of application using AngularJS Service

The first step is to create AngularJS application. Following code snippet is use to create AngularJS application. In this example, I have created one JavaScript file named app.js and placed the following code in this file.

  1. app.js  
  2. var app = angular.module("myapp", []);  
Second step is to create service and service definitions. In this example, I have created service in different file called "appService.js". Paste the following code in this file. In this AngularJS service object, I have created one function called "add". This function takes two argument and return the sum of these two.

appService.js
  1. app.service('appService', function () {  
  2.    this.add = function (a1, a2) {  
  3.       return parseInt(a1) + parseInt(a2);  
  4.    }  
  5. })  
Third step is to create controller object. Controller is a bridge between service and view. Controller pass the value of both the textboxes to the service function by using $scope.

appController.js

  1. app.controller("appController", function ($scope, appService) {  
  2.    $scope.Add = function () {  
  3.       $scope.total = appService.add($scope.digit1, $scope.digit2);  
  4.    }  
  5. });  
Last step is to create an HTML file. In HTML file, we need to register all scripts which are created by above code in head section. We need to also include angular.js file. Now paste the following code to html file.

HTML file (TestAgularJs.html)
  1. <html>  
  2. <head>  
  3.     <title>Understanding Services In AngularJS</title>  
  4.     <script src="angular.js"></script>  
  5.     <script src="app.js"></script>  
  6.     <script src="appService.js"></script>  
  7.     <script src="appController.js"></script>  
  8. </head>  
  9. <body ng-app="myapp">  
  10.     <h4>Service Example</h4>  
  11.       <div ng-controller="appController">  
  12.         <div width="100%" style="padding-top:10px;">  
  13.             <label>First Digit  : </label><input type="text" name="number" ng-model="digit1" />  
  14.         </div>  
  15.         <div width="100%" style="padding-top:10px;">  
  16.             <label>Second Digit : </label><input type="text" name="number" ng-model="digit2" />  
  17.         </div>  
  18.         <div width="100%" style="padding-top:10px;">  
  19.             <button ng-click="Add()">Add</button>  
  20.         </div>  
  21.         <div width="100%" style="padding-top:10px;">  
  22.             <label>digit1 + digit2: </label><input type="text" name="number" ng-model="total" />  
  23.         </div>  
  24.     </div>  
  25. </body>  
  26. </html>  
Output

output

Summary

Service in AngularJS is an important element in application. Service allows us to share data and behaviour with other object such as Controller. Services are singleton in AngularJS.