Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Difference between Service, Factory and Provider in AngularJS
// Source: https://groups.google.com/forum/#!topic/angular/hVrkvaHGOfc
// jsFiddle: http://jsfiddle.net/pkozlowski_opensource/PxdSP/14/
// author: Pawel Kozlowski
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() {
// In the provider function, you cannot inject any
// service or factory. This can only be done at the
// "$get" method.
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()];
}​
@crabmusket

This comment has been minimized.

Show comment Hide comment
@crabmusket

crabmusket Mar 10, 2013

I think it's clearer to write the $get function like this:

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

But it's a minor point. Fantastic example otherwise. Thank you!

I think it's clearer to write the $get function like this:

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

But it's a minor point. Fantastic example otherwise. Thank you!

@virtuallaura

This comment has been minimized.

Show comment Hide comment
@virtuallaura

virtuallaura Apr 11, 2013

I would love to see this example with service / factory / provider that wraps a resource.

I would love to see this example with service / factory / provider that wraps a resource.

@evangalen

This comment has been minimized.

Show comment Hide comment
@evangalen

evangalen Apr 11, 2013

@Mithrandir0x Thanks for your very useful Gist!

It was very useful while writing my blog about: "How to create (singleton) AngularJS services in 4 different ways"

@Mithrandir0x Thanks for your very useful Gist!

It was very useful while writing my blog about: "How to create (singleton) AngularJS services in 4 different ways"

@charlires

This comment has been minimized.

Show comment Hide comment
@charlires

charlires May 7, 2013

Thank you @Mithrandir0x it was very useful for me too.

Thank you @Mithrandir0x it was very useful for me too.

@jonahx

This comment has been minimized.

Show comment Hide comment
@jonahx

jonahx May 10, 2013

The "provider" example is better implemented with the revealing module pattern. In the form above, "name" is public: there really is no reason to have setName. To make "name" private as intended, rewrite it as:

myApp.provider('helloWorld', function() {

    var name = 'Default';

    return {
        $get: function() {
            return {
                sayHello: function() {
                    return "Hello, " + name + "!"
                }
            }
        },
        setName: function(newName) {
            name = newName;
        }
    };

});

Also this is a good egghead.io video on the subject

jonahx commented May 10, 2013

The "provider" example is better implemented with the revealing module pattern. In the form above, "name" is public: there really is no reason to have setName. To make "name" private as intended, rewrite it as:

myApp.provider('helloWorld', function() {

    var name = 'Default';

    return {
        $get: function() {
            return {
                sayHello: function() {
                    return "Hello, " + name + "!"
                }
            }
        },
        setName: function(newName) {
            name = newName;
        }
    };

});

Also this is a good egghead.io video on the subject

@maciejjankowski

This comment has been minimized.

Show comment Hide comment
@maciejjankowski

maciejjankowski May 14, 2013

Its nice to see how they work differently, but why do I need each of them? What do I use them for? Any real life examples on suggested use cases? Maybe a real app with rest and multiple controllers on single page?
Can anyone point me in the right direction? I'm struggling with a simple app wired with a resource and I have no clue how to organize things and make my productListCtrl talk to cartCtrl :/

Its nice to see how they work differently, but why do I need each of them? What do I use them for? Any real life examples on suggested use cases? Maybe a real app with rest and multiple controllers on single page?
Can anyone point me in the right direction? I'm struggling with a simple app wired with a resource and I have no clue how to organize things and make my productListCtrl talk to cartCtrl :/

@edgar-humberto

This comment has been minimized.

Show comment Hide comment
@edgar-humberto

edgar-humberto May 17, 2013

A believe a service is a singleton and a provider creates a new instance. So if you need to persist some info then a service might be the better way. Someone please correct me if I am wrong. A real world example would be to use a service to retrieve data from a server where you don't want to create a new object every time you need you XHR service object. To be honest i have not used providers at all. So I cannot really speak to their use cases.

I too would like to know a real use case for a provider.

A believe a service is a singleton and a provider creates a new instance. So if you need to persist some info then a service might be the better way. Someone please correct me if I am wrong. A real world example would be to use a service to retrieve data from a server where you don't want to create a new object every time you need you XHR service object. To be honest i have not used providers at all. So I cannot really speak to their use cases.

I too would like to know a real use case for a provider.

@Mithrandir0x

This comment has been minimized.

Show comment Hide comment
@Mithrandir0x

Mithrandir0x May 21, 2013

@jonahx True. Relying on variable scope for more privacy concerns is good, although I believe, when Pawel wrote this example, he was showing that when creating a new factory using the function given by the provider, the function was called with the keyword this bound to the provider object itself.

Instead of using a closure, you use this to access to methods and properties of the provider, which Factories and Service have no access to.

Owner

Mithrandir0x commented May 21, 2013

@jonahx True. Relying on variable scope for more privacy concerns is good, although I believe, when Pawel wrote this example, he was showing that when creating a new factory using the function given by the provider, the function was called with the keyword this bound to the provider object itself.

Instead of using a closure, you use this to access to methods and properties of the provider, which Factories and Service have no access to.

@gigablox

This comment has been minimized.

Show comment Hide comment
@gigablox

gigablox Jun 3, 2013

@pablodenadai

I feel like our solutions are very similar. However, I am using a service which includes various data manipulation methods. Please take a look the implimentation in this example and tell me how you would weigh each of our solutions in strengths/weaknesses --- with the goal in mind of course to share models across controllers.

You will see there is a lot of data manipulation to tweak model so it's ready for the view. I feel like a more complex example is going to serve us better for discussing what the best method is for solving this problem.

https://github.com/gigablox/angular-imgur-gallery
http://run.plnkr.co/plunks/akHTslTdRMvfe3KrnPeO/

gigablox commented Jun 3, 2013

@pablodenadai

I feel like our solutions are very similar. However, I am using a service which includes various data manipulation methods. Please take a look the implimentation in this example and tell me how you would weigh each of our solutions in strengths/weaknesses --- with the goal in mind of course to share models across controllers.

You will see there is a lot of data manipulation to tweak model so it's ready for the view. I feel like a more complex example is going to serve us better for discussing what the best method is for solving this problem.

https://github.com/gigablox/angular-imgur-gallery
http://run.plnkr.co/plunks/akHTslTdRMvfe3KrnPeO/

@mediaprojects

This comment has been minimized.

Show comment Hide comment
@mediaprojects

mediaprojects Jun 6, 2013

Simply great examples. Very useful, thanks a lot.

Simply great examples. Very useful, thanks a lot.

@WiechersV

This comment has been minimized.

Show comment Hide comment
@WiechersV

WiechersV Jun 19, 2013

Thank you very much, this is very enlightening!

I also recommend people to take a look at angular.js source code to understand it better, most specifically, search for the createInjector function, that's the one who hold all the logic of Angular DI, services, factory, services, etc.!

Thank you very much, this is very enlightening!

I also recommend people to take a look at angular.js source code to understand it better, most specifically, search for the createInjector function, that's the one who hold all the logic of Angular DI, services, factory, services, etc.!

@doup

This comment has been minimized.

Show comment Hide comment
@doup

doup Sep 3, 2013

You can't inject a service in app.config(), so if you want to pass a service to the provider just inject it in $get:

app.provider('settings', function () {
    this._settings = {};

    this.$get = ['cache', function (cache) {
        var settings = new Settings(cache);

        settings.setSettings(this._settings);

        return settings;
    }];

    this.setSettings = function (settings) {
        this._settings = settings;
    };
});

doup commented Sep 3, 2013

You can't inject a service in app.config(), so if you want to pass a service to the provider just inject it in $get:

app.provider('settings', function () {
    this._settings = {};

    this.$get = ['cache', function (cache) {
        var settings = new Settings(cache);

        settings.setSettings(this._settings);

        return settings;
    }];

    this.setSettings = function (settings) {
        this._settings = settings;
    };
});
@waskito

This comment has been minimized.

Show comment Hide comment
@waskito

waskito Nov 8, 2013

@doup you say that we can inject service in $get. Can I inject $cookieStore in $get ?

waskito commented Nov 8, 2013

@doup you say that we can inject service in $get. Can I inject $cookieStore in $get ?

@e911miri

This comment has been minimized.

Show comment Hide comment
@e911miri

e911miri Dec 25, 2013

Finally, I understand it

Finally, I understand it

@mrn-aglic

This comment has been minimized.

Show comment Hide comment
@mrn-aglic

mrn-aglic Jan 30, 2014

Thank you for the great examples!

Thank you for the great examples!

@AlexCppns

This comment has been minimized.

Show comment Hide comment
@AlexCppns

AlexCppns Feb 9, 2014

What I see is different ways of doing the same thing so far. Can I get an example where one MUST use a service for instance? When using a factory doesnt cut it and you have to use a provider?

What I see is different ways of doing the same thing so far. Can I get an example where one MUST use a service for instance? When using a factory doesnt cut it and you have to use a provider?

@andrezero

This comment has been minimized.

Show comment Hide comment
@andrezero

andrezero Mar 13, 2014

Most of the examples above give you a use case for a provider:

look in the first example how you can call setName() on the provider to configure the service. It's under "//hey, we can configure a provider!"

Most of the examples above give you a use case for a provider:

look in the first example how you can call setName() on the provider to configure the service. It's under "//hey, we can configure a provider!"

@LeftOverCoder

This comment has been minimized.

Show comment Hide comment
@LeftOverCoder

LeftOverCoder Mar 18, 2014

Service is singleton and simple version of Factory. While Factory is a simple version of Provider, Factory is a more flexable compared to service method, and a short handed for configuring a service when $get method is required. Provider creates new object by the $get factory function. Provider is not injectable during run phase or run time while all others are ( Constant, Variable, Service, and Factory), however, Provider is injectable during the configuration phase or compile time.

Provider should be used very sparely as you want to use compile time injection. Usually, Service does most of the job while Factory can deal with more sophisticated logic. Remember, Service is a singleton so if you need to create new object every time, use Factory instead.

Service is singleton and simple version of Factory. While Factory is a simple version of Provider, Factory is a more flexable compared to service method, and a short handed for configuring a service when $get method is required. Provider creates new object by the $get factory function. Provider is not injectable during run phase or run time while all others are ( Constant, Variable, Service, and Factory), however, Provider is injectable during the configuration phase or compile time.

Provider should be used very sparely as you want to use compile time injection. Usually, Service does most of the job while Factory can deal with more sophisticated logic. Remember, Service is a singleton so if you need to create new object every time, use Factory instead.

@dmitriz

This comment has been minimized.

Show comment Hide comment
@dmitriz

dmitriz Apr 22, 2014

Here is a very simple example of provider without 'this':
http://jsbin.com/xolom/2/edit

dmitriz commented Apr 22, 2014

Here is a very simple example of provider without 'this':
http://jsbin.com/xolom/2/edit

@sunew

This comment has been minimized.

Show comment Hide comment
@sunew

sunew May 26, 2014

@gigablox : Thanks for the super example, that really got it working for me. A question/comment: Instead of using events to signal data is ready, wouldn't it be a good just to return a promise. And then let the controller set then on the promise, and set data on the scope from then?

sunew commented May 26, 2014

@gigablox : Thanks for the super example, that really got it working for me. A question/comment: Instead of using events to signal data is ready, wouldn't it be a good just to return a promise. And then let the controller set then on the promise, and set data on the scope from then?

@hanmina

This comment has been minimized.

Show comment Hide comment
@hanmina

hanmina Jun 17, 2014

thanks for useful code block. but I would be happy if you explain each type, purpose and when to use which one.

hanmina commented Jun 17, 2014

thanks for useful code block. but I would be happy if you explain each type, purpose and when to use which one.

@joshids

This comment has been minimized.

Show comment Hide comment
@joshids

joshids Jun 24, 2014

  1. When you register the Service you return an object, when Angular needs to inject "service" into any component, it will inject this object.
  2. When you register the Factory, you return a constructor function. When angular needs to inject "service" into any component, it will first do a

new factoryReturnedFunction();

and then inject it. This will be done only for the first time service is requested. For all subsequent injections, object created first time will be used.
3. When you register a Provider, it has same behavior as Factory above. The function assigned to ...$get..., will be used as constructor function.

joshids commented Jun 24, 2014

  1. When you register the Service you return an object, when Angular needs to inject "service" into any component, it will inject this object.
  2. When you register the Factory, you return a constructor function. When angular needs to inject "service" into any component, it will first do a

new factoryReturnedFunction();

and then inject it. This will be done only for the first time service is requested. For all subsequent injections, object created first time will be used.
3. When you register a Provider, it has same behavior as Factory above. The function assigned to ...$get..., will be used as constructor function.

@expalmer

This comment has been minimized.

Show comment Hide comment
@expalmer

expalmer Jul 9, 2014

thanks for sharing, you help me alot to understand.

expalmer commented Jul 9, 2014

thanks for sharing, you help me alot to understand.

@ghost

This comment has been minimized.

Show comment Hide comment
@ghost

ghost Jul 21, 2014

Nice Info

ghost commented Jul 21, 2014

Nice Info

@SAM-BI

This comment has been minimized.

Show comment Hide comment
@SAM-BI

SAM-BI Jul 28, 2014

@Mithrandir0x, thank you for the example!
If we need a service and we define it using the "factory" method, is it write or false?

https://github.com/SAM-BI/jira-rest-angular

SAM-BI commented Jul 28, 2014

@Mithrandir0x, thank you for the example!
If we need a service and we define it using the "factory" method, is it write or false?

https://github.com/SAM-BI/jira-rest-angular

@codeandcats

This comment has been minimized.

Show comment Hide comment
@codeandcats

codeandcats Jun 11, 2015

Thanks, this is very helpful. :)

Thanks, this is very helpful. :)

@Hemalatah

This comment has been minimized.

Show comment Hide comment
@Hemalatah

Hemalatah Aug 25, 2015

Thanks much for the explanation. would you tell me, where to use which, I mean, how to make a right choice among them?
Appreciate your time

Thanks much for the explanation. would you tell me, where to use which, I mean, how to make a right choice among them?
Appreciate your time

@xis19

This comment has been minimized.

Show comment Hide comment
@xis19

xis19 Nov 18, 2015

Thanks for the helpful example.

xis19 commented Nov 18, 2015

Thanks for the helpful example.

@webineh

This comment has been minimized.

Show comment Hide comment
@webineh

webineh Mar 3, 2016

very thanks

webineh commented Mar 3, 2016

very thanks

@umangparekh001

This comment has been minimized.

Show comment Hide comment
@umangparekh001

umangparekh001 Feb 1, 2017

Many Thanks !

Many Thanks !

@kishorethalla

This comment has been minimized.

Show comment Hide comment
@kishorethalla

kishorethalla Mar 29, 2017

Nice explanation about Service / Provider / Factory, Very useful, Thank you very much !

Nice explanation about Service / Provider / Factory, Very useful, Thank you very much !

@shashankGopannagari

This comment has been minimized.

Show comment Hide comment
@shashankGopannagari

shashankGopannagari Nov 16, 2017

Nice Explanation. Helpful

Nice Explanation. Helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment