Understand AngularJS services

557-angular.jpg

 

AngularJS have 5 few ways to create service in AngularJS:
provider(); factory(); service(); value(); constant()
If you don’t know the difference then it’s better to reed official documentation or go through my notes. The point is to choose method consciously.

Before new service can be created AngularJS should know about this service. Service previously registered by $provide function.

Provider

So, the most fundamental method of create the service is:

$provide.provider().

app.config(function($provide){
     $provide.provider('testService', function() {
        this.$get = function(){
            var title = 'Project';
            return {
                title: title
            };
        }
    });
});Code language: PHP (php)

Working snippet on CodePen.

The benefit of this function is ability of configure this service in module.
app.config() with injected $provide function.

Also we can create provider directly from the module object and example of configuration some parameters.

app.provider('testService', function(){  
     this.titleId  = 1;
     this.$get = function(){
          var title = 'Project #' + this.titleId;          
          return {
               title: title
          };       
     }     
});
app.config(function(testServiceProvider){
     testServiceProvider.titleId = 2;
});Code language: JavaScript (javascript)

Working snippet on CodePen.

Instead of injecting the provide service in config - inject the testServiceProvider. (“Provider” automatically appends the name of the service).

Factory and Service

Investigating AngularJS core we can find factory() and service () function.
And it looks like just wrappers around provider() function.

factory and service function

Let’s compare factory() example:

app.factory('testService', function(){  
  return {
    testList: function(){
      return ['item1', 'item2', 'item3']
    }
  }
});
app.controller('TestController', function(testService, $scope) {
    $scope.testList = testService.testList();
});Code language: PHP (php)

with service() example:

app.service('testService', testService);
function testService() {
  TestServiceBase.call(this);    
  this.testList = function(id) {
    return ['item1 ' + this.version(id), 
            'item2 ' + this.version(id), 
            'item3 ' + this.version(id)];
  }  
}
function TestServiceBase() {}
TestServiceBase.prototype.version = function(id){ 
     return "version #" + id;
}
testService.prototype = Object.create(TestServiceBase.prototype);
app.controller('TestController', function(testService, $scope) {
    $scope.testList = testService.testList(2);
});Code language: JavaScript (javascript)

(working snippet of factory on CodePen)
(working snippet of service on CodePen)

As you see, difference between service and factory is that the function you passed to the service method will be treated as a constructor function and called with the JavaScript “new” operator. So, service() is better for inheritance.

Example of service can be pretty complicated. I will put here the same server of getting testList as simple as possible (CodePen).

app.service('testService', function(){
  this.testList = function() {
    return ['item1 ', 'item2 ', 'item3 '];
  }  
});Code language: JavaScript (javascript)

Value and Constant

Constant service — simply register service with injector. The only of functions here that is not wrapper of provider() function.

Constant is good for storing static data and can be injected in module configuration function and can’t be overwritten.

app.constant('constants', {
     APP_TITLE: 'Project',
     APP_VERSION: '1'
});
app.config(function(constants){
  console.log(constants.APP_TITLE);
});Code language: JavaScript (javascript)

Working snippet on CodePen.

Value — is shorthand of factory function. Good for use if you have nothing to inject. Value service can store functions with attributes.

app.value('testService', {
  retrieveVersion: function(version) {
    var status;
    if (version == 3) {status = 'alpha';}
    else if (version == 2) {status = 'stable';} 
    else if (version == 1) {status = 'legacy';}
    else {status = 'unknown';}
    return status;
  }
});Code language: JavaScript (javascript)

Working snippet on CodePen.

Web Development Services and Solutions Require Trusted Expertise Discover how Svitla Systems empowers your web development initiatives with innovative technologies and proven experience. Learn More

Using services

Using services in controllers or another services looks the same.
We inform injector what services to inject with dependency annotation.

DA as function parameter names (the simplest) 
(you can find example in any CodePen snippet above)

app.controller('TestController', function(testService) {
     console.log(testService);
});Code language: JavaScript (javascript)

DA as inline array annotation (good for minification)

app.controller('TestController', ['testService', function(testService) {
     console.log(testService);
}]);Code language: JavaScript (javascript)

With inject method

app.controller('TaskController', function(testService){
     console.log(testService);
}.$inject = ['testService'])Code language: JavaScript (javascript)

Summary

It’s better to create service with technique that is better match requirement for service functionality and it’s destination.

  • Provider — when we need to configure it dynamically in config function.

  • Factory — as a simple, regular service

  • Service — when we need to inherit something.

  • Value — when we don’t need any injections and have no dependency.

  • Constant — as a storage of values.


Thanks for great tutorial by Brice Wilson — AngularJS Services In-depth
It was the main inspiration for this article.

FAQ

What is an AngularJS service?

A service in AngularJS is a reusable singleton object or function that contains logic or data meant for sharing between controllers, directives, and even other services. It can easily be managed by Angular’s dependency injection mechanism. You may create services through the provider, factory, service, value, and constant methods. Use provider if you want to configure your service fully in config, then use factory mostly because it is simple; use service when you need a constructor and inheritance; and value when there is a need to register only plain values or simple objects without dependencies.

What is the purpose of AngularJS services?

The services of AngularJS are the basic organizing and sharing mechanisms between different code of an application. Actually, it encapsulates business logic, data, or utility functions for reuse and easy maintenance, besides separating concerns. In fact, services centralize common functionalities, thereby preventing code duplication in applications that can easily be scaled and tested. They play a critical role in managing the state of an application and providing a consistent mechanism for interacting with data and other external resources.

What is the difference between a factory and a service in AngularJS?

A factory and a service will both produce singletons in AngularJS; however, the method of their definition and instantiation varies. A factory is basically a function returning an object or another function. Angular will call this function, taking the returned value as its service instance. By comparison, a service comes across as a constructor function that Angular will instantiate using the new keyword; thus, methods and properties are attached to this inside it.

Why are we using services in Angular?

Services help to centralize logic or data that needs to be shared by different parts of the application. This will keep the controller and component purely presentational. Services will enforce good architecture by enforcing separation of concerns, which means having business rules, state management, and utility functions outside the view layer. They are implemented as singletons and managed by Angular’s dependency injection system, so they are simple to share, configure, and test. In general, services make applications maintainable and scalable – easier to reason about!

What are AngularJS filters and services?

Services in AngularJS are singleton reusable objects that may encapsulate business logic, data handling, or some utilities that can be shared among controllers, directives, and other components through dependency injection. They also ensure a good code organization structure by providing separation of concerns and eliminating duplication at every possible level of creation methods, including factory, service, provider, value, and constant. Filters are used for formatting the visible representation of data on templates, like date formatting, currency formatting, or array filtering, whereas services and filters separately make the code cleaner and more maintainable by separating the data processing and presentation logic from application controllers.