Service vs Factory vs Provider

09 Jul 2016

Most of the application frameworks have these terms - Services, factories and Providers. But those are less confusing as they differ too much in how we consume and different constructs for each.

But with AngularJS, the difference is more subtle so that the beginners will face the problem on selecting which one is correct for their current situation and most importantly -- What is the difference between these terminologies and their uses. In this post, I'll try to bring out the basic difference with code samples.

Services:

Injecting a service in an Angular module will return a function, that can be used to perform a specific operation.

Syntax:
module.service( 'serviceName', function );
Features:
  1. This will not hold any instance specific information; i.e., no configurations or environment specific values will be persisted within function
  2. This can be used a single instance through out an application - AngularJS creates services as a Singleton.
  3. Reusable with almost no modification.
Usage:

Used in situation where we need to have a set of utility or functionalities that are common & independent throughout the application. NOT just an application - it can be even between multiple applications.

Example:

UrlHelperService - This service can parse the given URL and provides you with the scheme, hostname, pathname, filename etc.,

AngularJS has many such services like $http, $q, $location etc., - that doesn't depend upon environment specific params except the provided input for processing.

Code sample:
myApp.service('helloWorldFromService', function() {
    this.sayHello = function() {
        return "Hello, World!";
    };
});


Factory:

Injecting a factory in an AngularJS module will return a value - a JavaScript object that can hold multiple properties or functions.

Syntax:
module.factory( 'factoryName', function );
Features:
  1. Returns set of values that we can use to process the data in our application.
  2. Mostly used to perform project specific tasks and returns the value of the operation.
  3. Factories can have dependency on multiple services like $http, $q etc.,
  4. There can be multiple instance of factories performing the different set of operation, based on the values set through the Setter functions.
Example:

Get list of articles from an API endpoint in a paged data fashion or get the stock information of a particular company or get weather information of a place provided.

Code sample:
myApp.factory('helloWorldFromFactory', function() {
    return {
        sayHello: function() {
            return "Hello, World!";
        }
    };
});


Provider:

Injecting a factory in an AngularJS module will return a function with $get - Provider function. Providers are same as services but we can inject the project specific configuration during the Configuration phase.

Syntax:
module.provider( 'providerName', function );
Feature:
  1. Provider allows your services to be configured with the initial application level configurations or settings.
  2. You can have all reusable application code of an application bundled as a provider
Example:

In a project, you can define a Repository provider : so that when the application loads up, you can set the repository type using app.config i.e., Where do you want to post the data ? to an API that sends data to a email account or save data in a database server or a filesystem.

Code sample:
myApp.provider('helloWorld', function() {

    this.name = 'Default'; //Configurable value

    this.$get = function() { //Provider function
        var name = this.name;
        return {
            sayHello: function() {
                return "Hello, " + name + "!";
            }
        }
    };

    this.setName = function(name) {
        this.name = name;
    };
});

//We can configure based on current application          
myApp.config(function(helloWorldProvider){
    helloWorldProvider.setName('World');
});