AngularJS Services

An important feature of AngularJS is the services architecture. Using services architecture, AngularJS supports the concepts of "Separation of Concerns". Services are functions in JavaScript which are specialized in performing a specific task only. Owing to this property, this makes them a single entity which makes them easy to maintain and test. Call can be made to the services by controllers, filters based on the requirement. These services are normally injected using dependency injection mechanism present in AngularJS.

There are many inbuilt services in AngularJS. Some of them are $http, $route, $window, $location etc. Each of these services are responsible for a specific task. For example, to get the data from the server we need to make an AJAX call which is done using the $http service. In another example, to define the routing information, the service called $route is used. The inbuilt services in AngularJS always have '$' symbol as the prefix.


In case of AngularJS, there are two different ways of creating a service.

  • factory
  • service

Now, let us have a look about how these two methods are implemented and used.

Using factory method

In the factory method, firstly we define a factory and later assign a method to it.

var mainApp = angular.module("mainApp", []);
mainApp.factory('NewService', function() {
   var factory = {};
   
   factory.multiply = function(a, b) {
      return a * b
   }
   
   return factory;
}); 

Using service method

In the service method, we first define a service and later assign a method to it. Additionally, we also inject an already available service to it.

mainApp.service('CalcService', function(NewService){
   this.square = function(a) {
      return NewService.multiply(a,a);
   }
});