Getting Started with Angular – Service

In this blog post we will see some of the important built in services of angular and how to create custom services

Angular services

Services are reusable objects in angular which we use to distribute application logic across modules. Important features of services
1. Services are injected into controllers using dependency injection
2. Services are lazily instantiated only when required by controllers
3. Services are Singleton objects and same objects are used across different controllers

Inbuild Angular Service

There are many inbuilt angular services which we will see in detail later. You can find a list of services here

Creating Custom Services

Services are mainly used in angularjs to modularize your application and move common code to services.
Below we are creating a ‘testService’ with a single function ‘speak’.
For a service we need to create a new module and define a factory method.

var serviceMod = angular.module('ServiceMod', []);
serviceMod.factory('testService',function(){
  
  var service = {};
  service.words = [];
  service.speak = function(word){
     this.words.push(word);
     if(this.words.length > 3){
        alert(this.words.join(' '));
        this.words = [];
     }
  }
  return service;
  
});

Next we will inject this service into our controller.

var mainMod = angular.module('MainApp', ['ServiceMod']);
mainMod.controller('MainCtrl', ['$scope','testService',
    function ($scope,testService) {
      $scope.text = '';
      $scope.speak = function(text){
        testService.speak(text);
      }
    }
]);

And our html would be

<body ng-app='MainApp'>
    <div ng-controller='MainCtrl'>
      <div>
        <div>Text: <input type='text' ng-model='text' /></div>
        <button type='button' ng-click='speak(text);'>Speak</button>
      </div>
    </div>
</body>

In the above code, you need to click 3 times on speak button to alert the text.

Above we have created a very simple service, we can inject this service into multiple controllers.

Custom Service With Dependency

Now we will create another service, which will depend on inbuilt angular services. Dependency Injection of services is handled same way as it is done for controllers.

var serviceMod = angular.module('ServiceMod', []);
serviceMod.factory('testService',['$log','$http',
  function($log,$http){
  
    var service = {};
    service.speak = function(){
       $log.info('Spoke');
    }
    return service;
  
  }
]);

In the above service i have injected $log and $http, both inbuilt angular services.