dependency injection - AngularJS: Service vs provider vs factory -
what differences between service
, provider
, factory
in angularjs?
from angularjs mailing list got an amazing thread explains service vs factory vs provider , injection usage. compiling answers:
services
syntax: module.service( 'servicename', function );
result: when declaring servicename injectable argument you provided instance of function. in other words new functionyoupassedtoservice()
.
factories
syntax: module.factory( 'factoryname', function );
result: when declaring factoryname injectable argument provided the value returned invoking function reference passed module.factory.
providers
syntax: module.provider( 'providername', function );
result: when declaring providername injectable argument you provided with (new providerfunction()).$get()
. constructor function instantiated before $get method called - providerfunction
function reference passed module.provider.
providers have advantage can configured during module configuration phase.
see here provided code.
here's great further explanation misko:
provide.value('a', 123); function controller(a) { expect(a).toequal(123); }
in case injector returns value is. if want compute value? use factory
provide.factory('b', function(a) { return a*2; }); function controller(b) { expect(b).toequal(246); }
so factory
function responsible creating value. notice factory function can ask other dependencies.
but if want more oo , have class called greeter?
function greeter(a) { this.greet = function() { return 'hello ' + a; } }
then instantiate have write
provide.factory('greeter', function(a) { return new greeter(a); });
then ask 'greeter' in controller this
function controller(greeter) { expect(greeter instanceof greeter).tobe(true); expect(greeter.greet()).toequal('hello 123'); }
but way wordy. shorter way write provider.service('greeter', greeter);
but if wanted configure greeter
class before injection? 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 can this:
angular.module('abc', []).config(function(greeter2provider) { greeter2provider.setsalutation('halo'); }); function controller(greeter2) { expect(greeter2.greet()).toequal('halo 123'); }
as side note, service
, factory
, , value
derived 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; }); };
Comments
Post a Comment