-4

I found that there are many answers online and here in stack overflow. But, none clarifies as to which one to use in which scenario as all three can perform the same set of functions?

Please clarify.

Rohit Rane
  • 2,790
  • 6
  • 25
  • 41
  • 6
    Possible duplicate of [AngularJS: Service vs provider vs factory](http://stackoverflow.com/questions/15666048/angularjs-service-vs-provider-vs-factory) – Ankh Jan 29 '16 at 09:24
  • Also see this one in the official docs: https://docs.angularjs.org/guide/providers – Anticom Jan 29 '16 at 09:29

1 Answers1

1

A provider is a configurable service. If you create a Foo service with provider(), you are able to use a FooProvider in a config() block:

angular.module('MyApp', [])
    .provider('Foo', function () {
        ...
    })
    .config(function (FooProvider) {
        FooProvider.something('bar');
    })
    .run(function (Foo) {
        ...
    });

For a trivial example of what you might want to use this for, see $logProvider.

If you don't need a configurable ...Provider for your service, the factory() or service() methods make it easier to create your service, since you don't need to do the complicated provider setup. factory/service are merely shorthand convenience constructors if you don't need a provider.

The difference between factory and service is that factory accepts a typical callback function, while service expects a "class" which it will instantiate with new. E.g.:

// Javascript "class"
function Foo() {
    ...
}
Foo.prototype.bar = ...;

angular.module('MyApp', [])
    .service('Foo', Foo)
    .factory('Bar', function () {
        ...
    })
    .run(function (Foo, Bar) {
        ...
    });

For more specifics on how to write a provider or provider-less service, see $provide and the guide.

deceze
  • 510,633
  • 85
  • 743
  • 889