with - AngularJS: Service vs provider vs factory




difference between service factory and provider in angularjs with example (20)

JS Fiddle Demo

" Hello world " example with factory / service / provider:

var myApp = angular.module('myApp', []);

//service style, probably the simplest one
myApp.service('helloWorldFromService', function() {
    this.sayHello = function() {
        return "Hello, World!";
    };
});

//factory style, more involved but more sophisticated
myApp.factory('helloWorldFromFactory', function() {
    return {
        sayHello: function() {
            return "Hello, World!";
        }
    };
});
    
//provider style, full blown, configurable version     
myApp.provider('helloWorld', function() {

    this.name = 'Default';

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

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

//hey, we can configure a provider!            
myApp.config(function(helloWorldProvider){
    helloWorldProvider.setName('World');
});
        

function MyCtrl($scope, helloWorld, helloWorldFromFactory, helloWorldFromService) {
    
    $scope.hellos = [
        helloWorld.sayHello(),
        helloWorldFromFactory.sayHello(),
        helloWorldFromService.sayHello()];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="myApp">
<div ng-controller="MyCtrl">
    {{hellos}}
</div>
</body>

What are the differences between a Service, Provider and Factory in AngularJS?


Factory

You give AngularJS a function, AngularJS will cache and inject the return value when the factory is requested.

Example:

app.factory('factory', function() {
    var name = '';
    // Return value **is** the object that will be injected
    return {
        name: name;
    }
})

Usage:

app.controller('ctrl', function($scope, factory) {
     $scope.name = factory.name;
});

Service

You give AngularJS a function, AngularJS will call new to instantiate it. It is the instance that AngularJS creates that will be cached and injected when the service is requested. Since new was used to instantiate the service, the keyword this is valid and refers to the instance.

Example:

app.service('service', function() {
     var name = '';
     this.setName = function(newName) {
         name = newName;
     }
     this.getName = function() {
         return name;
     }
});

Usage:

app.controller('ctrl', function($scope, service) {
   $scope.name = service.getName();
});

Provider

You give AngularJS a function, and AngularJS will call its $get function. It is the return value from the $get function that will be cached and injected when the service is requested.

Providers allow you to configure the provider before AngularJS calls the $get method to get the injectible.

Example:

app.provider('provider', function() {
     var name = '';
     this.setName = function(newName) {
          name = newName;
     }
     this.$get = function() {
         return {
            name: name
         }
     }
})

Usage (as an injectable in a controller)

app.controller('ctrl', function($scope, provider) {
    $scope.name = provider.name;
});

Usage (configuring the provider before $get is called to create the injectable)

app.config(function(providerProvider) {
    providerProvider.setName('John');
});

Factory: The factory you actually create an object inside of the factory and return it.
service: The service you just have a standard function that uses the this keyword to define function.
provider: The provider there’s a $get you define and it can be used to get the object that returns the data.


Service vs provider vs factory:

I am trying to keep it simple. It's all about basic JavaScript concept.

First of all, let's talk about services in AngularJS!

What is Service: In AngularJS, Service is nothing but a singleton JavaScript object which can store some useful methods or properties. This singleton object is created per ngApp(Angular app) basis and it is shared among all the controllers within current app. When Angularjs instantiate a service object, it register this service object with a unique service name. So each time when we need service instance, Angular search the registry for this service name, and it returns the reference to service object. Such that we can invoke method, access properties etc on the service object. You may have question whether you can also put properties, methods on scope object of controllers! So why you need service object? Answers is: services are shared among multiple controller scope. If you put some properties/methods in a controller's scope object , it will be available to current scope only. But when you define methods, properties on service object, it will be available globally and can be accessed in any controller's scope by injecting that service.

So if there are three controller scope, let it be controllerA, controllerB and controllerC, all will share same service instance.

<div ng-controller='controllerA'>
    <!-- controllerA scope -->
</div>
<div ng-controller='controllerB'>
    <!-- controllerB scope -->
</div>
<div ng-controller='controllerC'>
    <!-- controllerC scope -->
</div>

How to create a service?

AngularJS provide different methods to register a service. Here we will concentrate on three methods factory(..),service(..),provider(..);

Use this link for code reference

Factory function:

We can define a factory function as below.

factory('serviceName',function fnFactory(){ return serviceInstance;})

AngularJS provides 'factory('serviceName', fnFactory)' method which takes two parameter, serviceName and a JavaScript function. Angular creates service instance by invoking the function fnFactory() such as below.

var serviceInstace = fnFactory();

The passed function can define a object and return that object. AngularJS simply stores this object reference to a variable which is passed as first argument. Anything which is returned from fnFactory will be bound to serviceInstance . Instead of returning object , we can also return function, values etc, Whatever we will return , will be available to service instance.

Example:

var app= angular.module('myApp', []);
//creating service using factory method
app.factory('factoryPattern',function(){
  var data={
    'firstName':'Tom',
    'lastName':' Cruise',
    greet: function(){
      console.log('hello!' + this.firstName + this.lastName);
    }
  };

  //Now all the properties and methods of data object will be available in our service object
  return data;
});

Service Function:

service('serviceName',function fnServiceConstructor(){})

It's the another way, we can register a service. The only difference is the way AngularJS tries to instantiate the service object. This time angular uses 'new' keyword and call the constructor function something like below.

var serviceInstance = new fnServiceConstructor();

In the constructor function we can use 'this' keyword for adding properties/methods to the service object. example:

//Creating a service using the service method
var app= angular.module('myApp', []);
app.service('servicePattern',function(){
  this.firstName ='James';
  this.lastName =' Bond';
  this.greet = function(){
    console.log('My Name is '+ this.firstName + this.lastName);
  };
});

Provider function:

Provider() function is the another way for creating services. Let we are interested to create a service which just display some greeting message to the user. But we also want to provide a functionality such that user can set their own greeting message. In technical terms we want to create configurable services. How can we do this ? There must be a way, so that app could pass their custom greeting messages and Angularjs would make it available to factory/constructor function which create our services instance. In such a case provider() function do the job. using provider() function we can create configurable services.

We can create configurable services using provider syntax as given below.

/*step1:define a service */
app.provider('service',function serviceProviderConstructor(){});

/*step2:configure the service */
app.config(function configureService(serviceProvider){});

How does provider syntax internally work?

1.Provider object is created using constructor function we defined in our provider function.

var serviceProvider = new serviceProviderConstructor();

2.The function we passed in app.config(), get executed. This is called config phase, and here we have a chance to customize our service.

configureService(serviceProvider);

3.Finally service instance is created by calling $get method of serviceProvider.

serviceInstance = serviceProvider.$get()

Sample code for creating service using provide syntax:

var app= angular.module('myApp', []);
app.provider('providerPattern',function providerConstructor(){
  //this function works as constructor function for provider
  this.firstName = 'Arnold ';
  this.lastName = ' Schwarzenegger' ;
  this.greetMessage = ' Welcome, This is default Greeting Message' ;
  //adding some method which we can call in app.config() function
  this.setGreetMsg = function(msg){
    if(msg){
      this.greetMessage =  msg ;
    }
  };

  //We can also add a method which can change firstName and lastName
  this.$get = function(){
    var firstName = this.firstName;
    var lastName = this.lastName ;
    var greetMessage = this.greetMessage;
    var data={
       greet: function(){
         console.log('hello, ' + firstName + lastName+'! '+ greetMessage);
       }
    };
    return data ;
  };
});

app.config(
  function(providerPatternProvider){
    providerPatternProvider.setGreetMsg(' How do you do ?');
  }
);

Working Demo

Summary:


Factory use a factory function which return a service instance. serviceInstance = fnFactory();

Service use a constructor function and Angular invoke this constructor function using 'new' keyword for creating the service instance. serviceInstance = new fnServiceConstructor();

Provider defines a providerConstructor function, this providerConstructor function defines a factory function $get . Angular calls $get() to create the service object. Provider syntax has an added advantage of configuring the service object before it get instantiated. serviceInstance = $get();


Understanding AngularJS Factory, Service and Provider

All of these are used to share reusable singleton objects. It helps to share reusable code across your app/various components/modules.

From Docs Service/Factory:

  • Lazily instantiated – Angular only instantiates a service/factory when an application component depends on it.
  • Singletons – Each component dependent on a service gets a reference to the single instance generated by the service factory.

Factory

A factory is function where you can manipulate/add logic before creating an object, then the newly created object gets returned.

app.factory('MyFactory', function() {
    var serviceObj = {};
    //creating an object with methods/functions or variables
    serviceObj.myFunction = function() {
        //TO DO:
    };
    //return that object
    return serviceObj;
});

Usage

It can be just a collection of functions like a class. Hence, it can be instantiated in different controllers when you are injecting it inside your controller/factory/directive functions. It is instantiated only once per app.

Service

Simply while looking at the services think about the array prototype. A service is a function which instantiates a new object using the 'new' keyword. You can add properties and functions to a service object by using the this keyword. Unlike a factory, it doesn't return anything (it returns an object which contains methods/properties).

app.service('MyService', function() {
    //directly binding events to this context
    this.myServiceFunction = function() {
        //TO DO:
    };
});

Usage

Use it when you need to share a single object throughout the application. For example, authenticated user details, share-able methods/data, Utility functions etc.

Provider

A provider is used to create a configurable service object. You can configure the service setting from config function. It returns a value by using the $get() function. The $get function gets executed on the run phase in angular.

app.provider('configurableService', function() {
    var name = '';
    //this method can be be available at configuration time inside app.config.
    this.setName = function(newName) {
        name = newName;
    };
    this.$get = function() {
        var getName = function() {
             return name;
        };
        return {
            getName: getName //exposed object to where it gets injected.
        };
    };
});

Usage

When you need to provide module-wise configuration for your service object before making it available, eg. suppose you want to set your API URL on basis of your Environment like dev, stage or prod

NOTE

Only provider will be available in config phase of angular, while service & factory are not.

Hope this has cleared up your understanding about Factory, Service and Provider.


After reading all these post It created more confuse for me.. But still all is worthfull information.. finally I found following table which will give information with simple comparision

  • The injector uses recipes to create two types of objects: services and special purpose objects
  • There are five recipe types that define how to create objects: Value, Factory, Service, Provider and Constant.
  • Factory and Service are the most commonly used recipes. The only difference between them is that the Service recipe works better for objects of a custom type, while the Factory can produce JavaScript primitives and functions.
  • The Provider recipe is the core recipe type and all the other ones are just syntactic sugar on it.
  • Provider is the most complex recipe type. You don't need it unless you are building a reusable piece of code that needs global configuration.
  • All special purpose objects except for the Controller are defined via Factory recipes.

And for beginner understand:- This may not correct use case but in high level this is what usecase for these three.

  1. If you want to use in angular module config function should created as provider

angular.module('myApp').config(function($testProvider){
$testProvider.someFunction();
})
  1. Ajax call or third party integrations needs to be service.
  2. For Data manipulations create it as factory

For basic scenarios factory&Service behaves same.


All the good answers already. I would like to add few more points on Service and Factory. Along with the difference between service/factory. And one can also have questions like:

  1. Should I use service or factory? What’s the difference?
  2. Is they do same or have same behaviour?

Lets start with the difference between Service and factory:

  1. Both are Singletons: Whenever Angular find these as a dependency first time,it create a single instance of service/factory. Once the instance is created, same instance is used forever.

  2. Can be used to model an object with behavior: They can both have methods, internal state variables, and so on. Though the way you write that code will differ.

Services:

A service is a constructor function, and Angular will instantiate it by calling new yourServiceName(). This means a couple of things.

  1. Functions and instance variables will be properties of this.
  2. You don’t need to return a value. When Angular calls new yourServiceName(), it’ll receive the this object with all the properties you put on it.

Sample Example:

angular.service('MyService', function() {
  this.aServiceVariable = "Ved Prakash"
  this.aServiceMethod = function() {
    return //code
  };
});

When Angular injects this MyService service into a controller that depends on it, that controller will get a MyService that it can call functions on, e.g. MyService.aServiceMethod ().

Be careful with this:

Since the constructed service is an object, the methods inside it can refer to this when they’re called:

angular.service('ScoreKeeper', function($http) {
  this.score = 0;

  this.getScore = function() {
    return this.score;
  };

  this.setScore = function(newScore) {
    this.score = newScore;
  };

  this.addOne = function() {
    this.score++;
  };
});

You might be tempted to call ScoreKeeper.setScore in a promise chain, for instance if you initialized the score by grabbing it from the server: $http.get('/score').then(ScoreKeeper.setScore). The trouble with this is that ScoreKeeper.setScore will be called with this bound to null and you’ll get errors. The better way would be $http.get('/score').then(ScoreKeeper.setScore.bind(ScoreKeeper)). Whether you choose to use this in your service methods or not, be careful how you call them.

Returning a Value from a Service:

Due to how JavaScript constructors work, if you return a complex value (i.e., an Object) from a constructor function, the caller will get that Object instead of the this instance.

This means that you can basically copy-paste the factory example from below, replace factory with service, and it’ll work:

angular.service('MyService', function($http) {
  var api = {};

  api.aServiceMethod= function() {
    return $http.get('/users');
  };
  return api;
});

So when Angular constructs your service with new MyService(), it’ll get that api object instead of the MyService instance.

This is the behavior for any complex values (objects, functions) but not for primitive types.

Factories:

A factory is a plain old function that returns a value. The return value is what gets injected into things that depend on the factory. A typical factory pattern in Angular is to return an object with functions as properties, like this:

angular.factory('MyFactory', function($http) {
  var api = {};

  api.aFactoryMethod= function() {
    return $http.get('/users');
  };

  return api;
});

The injected value for a factory dependency is the factory’s return value, and it doesn’t have to be an object. It could be a function

Answers for above 1 and 2 questions:

For the most part, just stick with using factories for everything. Their behavior is easier to understand. There’s no choice to make about whether to return a value or not, and furthermore, no bugs to be introduced if you do the wrong thing.

I still refer to them as “services” when I’m talking about injecting them as dependencies, though.

Service/Factory behavior is very similar, and some people will say that either one is fine. That’s somewhat true, but I find it easier to follow the advice of John Papa’s style guide and just stick with factories.**


An additional clarification is that factories can create functions/primitives, while services cannot. Check out this jsFiddle based on Epokk's: http://jsfiddle.net/skeller88/PxdSP/1351/.

The factory returns a function that can be invoked:

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

The factory can also return an object with a method that can be invoked:

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

The service returns an object with a method that can be invoked:

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

For more details, see a post I wrote on the difference: http://www.shanemkeller.com/tldr-services-vs-factories-in-angular/


Based on memory purposes, controllers are instantiated only when they are needed and discarded when they are not. Because of this, every time you switch a route or reload a page, Angular cleans up the current controller. Services however provide a means for keeping data around for the lifetime of an application while they also can be used across different controllers in a consistent manner.

Angular provides us with three ways to create and register our own service.

1) Factory

2) Service

3) Provider

Factory: A factory is a simple function which allows you to add some logic before creating the object. It returns the created object.

It is just a collection of functions like a class. Hence, it can be instantiated in different controllers when you are using it with constructor function.

Service: A service is a constructor function which creates the object using new keyword. You can add properties and functions to a service object by using this keyword. Unlike factory, it doesn’t return anything.

It is a singleton object. Use it when you need to share a single object across the application. For example, authenticated user details.

Provider: A provider is used to create a configurable service object. It returns value by using $get() function.

When you need to provide module-wise configuration for your service object before making it available.

Run the following code and see the output.

<!DOCTYPE html>
<html ng-app="app">
<head>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.1/angular.min.js"></script>
    <meta charset=utf-8 />
    <title>JS Bin</title>
</head>
<body ng-controller="MyCtrl">
    {{serviceOutput}}
    <br/><br/>
    {{factoryOutput}}
    <br/><br/>
    {{providerOutput}}
    <script>
        var app = angular.module( 'app', [] );
        var MyFunc = function() {
            this.name = "default name";
            this.$get = function() {
                this.name = "new name"
                return "Hello from MyFunc.$get(). this.name = " + this.name;
            };
            return "Hello from MyFunc(). this.name = " + this.name;
        };
        // returns the actual function
        app.service( 'myService', MyFunc );
        // returns the function's return value
        app.factory( 'myFactory', MyFunc );
        // returns the output of the function's $get function
        app.provider( 'myProv', MyFunc );
        function MyCtrl( $scope, myService, myFactory, myProv ) {
            $scope.serviceOutput = "myService = " + myService;
            $scope.factoryOutput = "myFactory = " + myFactory;
            $scope.providerOutput = "myProvider = " + myProv;
        }
    </script>
</body>
</html>

Essentially, Provider, Factory, and Service are all Services. A Factory is a special case of a Service when all you need is a $get() function, allowing you to write it with less code.

The major differences among Services, Factories, and Providers are their complexities. Services are the simplest form, Factories are a little more robust, and Providers are configurable at runtime.

Here is a summary of when to use each:

Factory: The value you are providing needs to be calculated based on other data.

Service: You are returning an object with methods.

Provider: You want to be able to configure, during the config phase, the object that is going to be created before it’s created. Use the Provider mostly in the app config, before the app has fully initialized.


For me, the revelation came when I realized that they all work the same way: by running something once, storing the value they get, and then cough up that same stored value when referenced through dependency injection.

Say we have:

app.factory('a', fn);
app.service('b', fn);
app.provider('c', fn);

The difference between the three is that:

  1. a's stored value comes from running fn.
  2. b’s stored value comes from newing fn.
  3. c’s stored value comes from first getting an instance by newing fn, and then running a $get method of the instance.

Which means there’s something like a cache object inside AngularJS, whose value of each injection is only assigned once, when they've been injected the first time, and where:

cache.a = fn()
cache.b = new fn()
cache.c = (new fn()).$get()

This is why we use this in services, and define a this.$get in providers.


From the AngularJS mailing list I got an amazing thread that explains service vs factory vs provider and their injection usage. Compiling the answers:

Services

Syntax: module.service( 'serviceName', function );
Result: When declaring serviceName as an injectable argument you will be provided with an instance of the function. In other words new FunctionYouPassedToService().

Factories

Syntax: module.factory( 'factoryName', function );
Result: When declaring factoryName as an injectable argument you will be provided with the value that is returned by invoking the function reference passed to module.factory.

Providers

Syntax: module.provider( 'providerName', function );
Result: When declaring providerName as an injectable argument you will be provided with (new ProviderFunction()).$get(). The constructor function is instantiated before the $get method is called - ProviderFunction is the function reference passed to module.provider.

Providers have the advantage that they can be configured during the module configuration phase.

See here for the provided code.

Here's a great further explanation by Misko:

provide.value('a', 123);

function Controller(a) {
  expect(a).toEqual(123);
}

In this case the injector simply returns the value as is. But what if you want to compute the value? Then use a factory

provide.factory('b', function(a) {
  return a*2;
});

function Controller(b) {
  expect(b).toEqual(246);
}

So factory is a function which is responsible for creating the value. Notice that the factory function can ask for other dependencies.

But what if you want to be more OO and have a class called Greeter?

function Greeter(a) {
  this.greet = function() {
    return 'Hello ' + a;
  }
}

Then to instantiate you would have to write

provide.factory('greeter', function(a) {
  return new Greeter(a);
});

Then we could ask for 'greeter' in controller like this

function Controller(greeter) {
  expect(greeter instanceof Greeter).toBe(true);
  expect(greeter.greet()).toEqual('Hello 123');
}

But that is way too wordy. A shorter way to write this would be provider.service('greeter', Greeter);

But what if we wanted to configure the Greeter class before the injection? Then we could write

provide.provider('greeter2', function() {
  var salutation = 'Hello';
  this.setSalutation = function(s) {
    salutation = s;
  }

  function Greeter(a) {
    this.greet = function() {
      return salutation + ' ' + a;
    }
  }

  this.$get = function(a) {
    return new Greeter(a);
  };
});

Then we can do this:

angular.module('abc', []).config(function(greeter2Provider) {
  greeter2Provider.setSalutation('Halo');
});

function Controller(greeter2) {
  expect(greeter2.greet()).toEqual('Halo 123');
}

As a side note, service, factory, and value are all derived from provider.

provider.service = function(name, Class) {
  provider.provide(name, function() {
    this.$get = function($injector) {
      return $injector.instantiate(Class);
    };
  });
}

provider.factory = function(name, factory) {
  provider.provide(name, function() {
    this.$get = function($injector) {
      return $injector.invoke(factory);
    };
  });
}

provider.value = function(name, value) {
  provider.factory(name, function() {
    return value;
  });
};

I know a lot of excellent answer but I have to share my experience of using
1. service for most cases of default
2. factory used to create the service that specific instance

// factory.js ////////////////////////////
(function() {
'use strict';
angular
    .module('myApp.services')
    .factory('xFactory', xFactoryImp);
xFactoryImp.$inject = ['$http'];

function xFactoryImp($http) {
    var fac = function (params) {
        this._params = params; // used for query params
    };

    fac.prototype.nextPage = function () {
        var url = "/_prc";

        $http.get(url, {params: this._params}).success(function(data){ ...
    }
    return fac;
}
})();

// service.js //////////////////////////
(function() {
'use strict';
angular
    .module('myApp.services')
    .service('xService', xServiceImp);
xServiceImp.$inject = ['$http'];

function xServiceImp($http) {  
    this._params = {'model': 'account','mode': 'list'};

    this.nextPage = function () {
        var url = "/_prc";

        $http.get(url, {params: this._params}).success(function(data){ ...
    }       
}
})();

and using:

controller: ['xFactory', 'xService', function(xFactory, xService){

        // books = new instance of xFactory for query 'book' model
        var books = new xFactory({'model': 'book', 'mode': 'list'});

        // accounts = new instance of xFactory for query 'accounts' model
        var accounts = new xFactory({'model': 'account', 'mode': 'list'});

        // accounts2 = accounts variable
        var accounts2 = xService;
... 

I noticed something interesting when playing around with providers.

Visibility of injectables is different for providers than it is for services and factories. If you declare an AngularJS "constant" (for example, myApp.constant('a', 'Robert');), you can inject it into services, factories, and providers.

But if you declare an AngularJS "value" (for example., myApp.value('b', {name: 'Jones'});), you can inject it into services and factories, but NOT into the provider-creating function. You can, however, inject it into the $get function that you define for your provider. This is mentioned in the AngularJS documentation, but it's easy to miss. You can find it on the %provide page in the sections on the value and constant methods.

http://jsfiddle.net/R2Frv/1/

<div ng-app="MyAppName">
    <div ng-controller="MyCtrl">
        <p>from Service: {{servGreet}}</p>
        <p>from Provider: {{provGreet}}</p>
    </div>
</div>
<script>
    var myApp = angular.module('MyAppName', []);

    myApp.constant('a', 'Robert');
    myApp.value('b', {name: 'Jones'});

    myApp.service('greetService', function(a,b) {
        this.greeter = 'Hi there, ' + a + ' ' + b.name;
    });

    myApp.provider('greetProvider', function(a) {
        this.firstName = a;
        this.$get = function(b) {
            this.lastName = b.name;
            this.fullName = this.firstName + ' ' + this.lastName;
            return this;
        };
    });

    function MyCtrl($scope, greetService, greetProvider) {
        $scope.servGreet = greetService.greeter;
        $scope.provGreet = greetProvider.fullName;
    }
</script>

Let's discuss the three ways of handling business logic in AngularJS in a simple way: (Inspired by Yaakov's Coursera AngularJS course)

SERVICE:

Syntax:

app.js

 var app = angular.module('ServiceExample',[]);
 var serviceExampleController =
              app.controller('ServiceExampleController', ServiceExampleController);
 var serviceExample = app.service('NameOfTheService', NameOfTheService);

 ServiceExampleController.$inject = ['NameOfTheService'] //protects from minification of js files

function ServiceExampleController(NameOfTheService){
     serviceExampleController = this;
     serviceExampleController.data = NameOfTheService.getSomeData();
 }

function NameOfTheService(){
     nameOfTheService = this;
     nameOfTheService.data = "Some Data";
     nameOfTheService.getSomeData = function(){
           return nameOfTheService.data;
     }     
}

index.html

<div ng-controller = "ServiceExampleController as serviceExample">
   {{serviceExample.data}}
</div>

Features of Service:

  1. Lazily Instantiated: If it is not injected it won't be instantiated ever. So to use it will have to inject it to a module.
  2. Singleton: If injected to multiple modules, all will have access to only one particular instance. That is why very convenient to share data across different controllers.

FACTORY

First let's have a look at the syntax:

app.js:

var app = angular.module('FactoryExample',[]);
var factoryController = app.controller('FactoryController', FactoryController);
var factoryExampleOne = app.factory('NameOfTheFactoryOne', NameOfTheFactoryOne);
var factoryExampleTwo = app.factory('NameOfTheFactoryTwo', NameOfTheFactoryTwo);

//first implementation where it returns a function
function NameOfTheFactoryOne(){
   var factory = function(){
      return new SomeService();
    }
   return factory;
}

//second implementation where an object literal would be returned
function NameOfTheFactoryTwo(){
   var factory = {
      getSomeService : function(){
          return new SomeService();
       }
    };
   return factory;
}

Now using the above two in the controller:

 var factoryOne = NameOfTheFactoryOne() //since it returns a function
 factoryOne.someMethod();

 var factoryTwo = NameOfTheFactoryTwo.getSomeService(); //accessing the object
 factoryTwo.someMethod();

Features of Factory:

  1. Follows the factory design pattern. The factory is a central place that produces new objects or functions.
  2. Not only produces singleton, but customizable services.
  3. The .service() method is a factory that always produces the same type of service, which is a singleton, and without any easy way to configure it's behavior. That .service() method is usually used as a shortcut for something that doesn't require any configuration whatsoever.

PROVIDER

Let's again have a look at the Syntax first:

angular.module('ProviderModule', [])
.controller('ProviderModuleController', ProviderModuleController)
.provider('ServiceProvider', ServiceProvider)
.config(Config); //optional

Config.$inject = ['ServiceProvider'];
function Config(ServiceProvider) {
  ServiceProvider.defaults.maxItems = 10; //some default value
}


ProviderModuleController.$inject = ['ServiceProvider'];
function ProviderModuleController(ServiceProvider) {
  //some methods
}

function ServiceProvider() {
  var provider = this;

  provider.defaults = {
    maxItems: 10
  };

  provider.$get = function () {
    var someList = new someListService(provider.defaults.maxItems);

    return someList;
  };
}

}

Features of Provider:

  1. Provider is the most flexible method of creating services in Angular.
  2. Not only we can create a factory that's dynamically configurable, but at the time of using the factory, with the provider method, we could custom configure the factory just once at the bootstrapping of our entire application.
  3. The factory can then be used throughout the application with custom settings. In other words, we can configure this factory before the application starts. In fact in the angular documentation it is mentioned that the provider method is what actually gets executed behind the scenes when we configure our services with either .service or .factory methods.
  4. The $get is a function that is directly attached to the provider instance. That function is a factory function. In other words, it's just like the one that we use to provide to the .factory method. In that function, we create our own service. This $get property, that's a function, is what makes the provider a provider. AngularJS expects the provider to have a $get property whose value is a function that Angular will treat as a factory function. But what makes this whole provider setup very special, is the fact that we can provide some config object inside the service provider, and that usually comes with defaults that we can later overwrite in the step, where we can configure the entire application.

Little late to the party. But I thought this is more helpful for who would like to learn (or have clarity) on developing Angular JS Custom Services using factory, service and provider methodologies.

I came across this video which explains clearly about factory, service and provider methodologies for developing AngularJS Custom Services:

https://www.youtube.com/watch?v=oUXku28ex-M

Source Code: http://www.techcbt.com/Post/353/Angular-JS-basics/how-to-develop-angularjs-custom-service

Code posted here is copied straight from the above source, to benefit readers.

The code for "factory" based custom service is as follows (which goes with both sync and async versions along with calling http service):

var app = angular.module("app", []);
app.controller('emp', ['$scope', 'calcFactory',
  function($scope, calcFactory) {
    $scope.a = 10;
    $scope.b = 20;

    $scope.doSum = function() {
      //$scope.sum = calcFactory.getSum($scope.a, $scope.b); //synchronous
      calcFactory.getSum($scope.a, $scope.b, function(r) { //aynchronous
        $scope.sum = r;
      });
    };

  }
]);

app.factory('calcFactory', ['$http', '$log',
  function($http, $log) {
    $log.log("instantiating calcFactory..");
    var oCalcService = {};

    //oCalcService.getSum = function(a,b){
    //	return parseInt(a) + parseInt(b);
    //};

    //oCalcService.getSum = function(a, b, cb){
    //	var s = parseInt(a) + parseInt(b);
    //	cb(s);
    //};

    oCalcService.getSum = function(a, b, cb) { //using http service

      $http({
        url: 'http://localhost:4467/Sum?a=' + a + '&b=' + b,
        method: 'GET'
      }).then(function(resp) {
        $log.log(resp.data);
        cb(resp.data);
      }, function(resp) {
        $log.error("ERROR occurred");
      });
    };

    return oCalcService;
  }
]);

The code for "service" methodology for Custom Services (this is pretty similar to 'factory', but different from syntax point of view):

var app = angular.module("app", []);
app.controller('emp', ['$scope', 'calcService', function($scope, calcService){
	$scope.a = 10;
	$scope.b = 20;

	$scope.doSum = function(){
		//$scope.sum = calcService.getSum($scope.a, $scope.b);
		
		calcService.getSum($scope.a, $scope.b, function(r){
			$scope.sum = r;
		});		
	};

}]);

app.service('calcService', ['$http', '$log', function($http, $log){
	$log.log("instantiating calcService..");
	
	//this.getSum = function(a,b){
	//	return parseInt(a) + parseInt(b);
	//};

	//this.getSum = function(a, b, cb){
	//	var s = parseInt(a) + parseInt(b);
	//	cb(s);
	//};

	this.getSum = function(a, b, cb){
		$http({
			url: 'http://localhost:4467/Sum?a=' + a + '&b=' + b,
			method: 'GET'
		}).then(function(resp){
			$log.log(resp.data);
			cb(resp.data);
		},function(resp){
			$log.error("ERROR occurred");
		});
	};

}]);

The code for "provider" methodology for Custom Services (this is necessary, if you would like to develop service which could be configured):

var app = angular.module("app", []);
app.controller('emp', ['$scope', 'calcService', function($scope, calcService){
	$scope.a = 10;
	$scope.b = 20;

	$scope.doSum = function(){
		//$scope.sum = calcService.getSum($scope.a, $scope.b);
		
		calcService.getSum($scope.a, $scope.b, function(r){
			$scope.sum = r;
		});		
	};

}]);

app.provider('calcService', function(){

	var baseUrl = '';

	this.config = function(url){
		baseUrl = url;
	};

	this.$get = ['$log', '$http', function($log, $http){
		$log.log("instantiating calcService...")
		var oCalcService = {};

		//oCalcService.getSum = function(a,b){
		//	return parseInt(a) + parseInt(b);
		//};

		//oCalcService.getSum = function(a, b, cb){
		//	var s = parseInt(a) + parseInt(b);
		//	cb(s);	
		//};

		oCalcService.getSum = function(a, b, cb){

			$http({
				url: baseUrl + '/Sum?a=' + a + '&b=' + b,
				method: 'GET'
			}).then(function(resp){
				$log.log(resp.data);
				cb(resp.data);
			},function(resp){
				$log.error("ERROR occurred");
			});
		};		

		return oCalcService;
	}];

});

app.config(['calcServiceProvider', function(calcServiceProvider){
	calcServiceProvider.config("http://localhost:4467");
}]);

Finally the UI which works with any of the above services:

<html>
<head>
	<title></title>
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js" ></script>
	<script type="text/javascript" src="t03.js"></script>
</head>
<body ng-app="app">
	<div ng-controller="emp">
		<div>
			Value of a is {{a}},
			but you can change
			<input type=text ng-model="a" /> <br>

			Value of b is {{b}},
			but you can change
			<input type=text ng-model="b" /> <br>

		</div>
		Sum = {{sum}}<br>
		<button ng-click="doSum()">Calculate</button>
	</div>
</body>
</html>

My understanding is very simple below.

Factory: You simply create an object inside of the factory and return it.

Service:

You just have a standard function that uses this keyword to define a function.

Provider:

There is a $get object that you define and it can be used to get the object that returns data.


Summary from Angular docs:

  • There are five recipe types that define how to create objects: Value, Factory, Service, Provider and Constant.
  • Factory and Service are the most commonly used recipes. The only difference between them is that the Service recipe works better for objects of a custom type, while the Factory can produce JavaScript primitives and functions.
  • The Provider recipe is the core recipe type and all the other ones are just syntactic sugar on it.
  • Provider is the most complex recipe type. You don't need it unless you are building a reusable piece of code that needs global configuration.


Best answers from SO:

https://.com/a/26924234/165673 (<-- GOOD) https://.com/a/27263882/165673
https://.com/a/16566144/165673


This answer address the topic/question

how Factory, Service and Constant — are just syntactic sugar on top of a provider recipe?

OR

how factory ,servic and providers are simailar internally

basically what happens is

When you make a factory() it sets you function provided in second argument to provider's $get and return it(provider(name, {$get:factoryFn })), all you get is provider but there is no property/method other than $get of that provider(means you can't configure this)

Source code of factory

function factory(name, factoryFn, enforce) {
    return provider(name, {
      $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
    });
};

When making a service() it return you providing a factory() with a function that injects the constructor (return the instance of the constructor you provided in your service) and returns it

Source code of service

function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
      return $injector.instantiate(constructor);
    }]);
};

So basically in both cases you eventually get a providers $get set to your function you provided , but you can give anything extra than $get as you can originally provide in provider() for config block


This is very confusing part for newbie and I have tried to clarify it in easy words

AngularJS Service: is used for sharing utility functions with the service reference in the controller. Service is singleton in nature so for one service only one instance is created in the browser and the same reference is used throughout the page.

In the service, we create function names as property with this object.

AngularJS Factory: the purpose of Factory is also same as Service however in this case we create a new object and add functions as properties of this object and at the end we return this object.

AngularJS Provider: the purpose of this is again same however Provider gives the output of it's $get function.

Defining and using Service, Factory and Provider are explained at http://www.dotnetfunda.com/articles/show/3156/difference-between-angularjs-service-factory-and-provider





angularjs-provider