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.
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.
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.