Agenda AngularJS Service Overview $provide functions: Provider Factory Service Value & Constant Decorator
Angular Services Angular services are singletons that carry out specific tasks . All services in Angular are instantiated lazily . There are three functions for creating generic services, with different levels of complexity and ability : Service Factory Provider
Registering Services You can register the service with the module either via the Module api or by using the $provide service in the module configuration function. var mi= angular.module ( ' myModule ' , []); mi.factory ( ' serviceId ' , function () { var shinyNewServiceInstance ; //factory function body that constructs shinyNewServiceInstance return shinyNewServiceInstance ; }); angular.module ( ' myModule ' , [], function ($provide) { $ provide.factory ( ' serviceId ' , function () { var shinyNewServiceInstance ; //factory function body that constructs shinyNewServiceInstance return shinyNewServiceInstance ; }); }); Option I Option II
$provide functions for creating generic services service(name , constructor ) you will be provided the actual function reference passed to module.service . factory(name, $ getFn ) you will be provided the value that is returned by invoking the function reference passed to module.factory . provider(name, provider ) you will be provided the value that is returned by invoking the $get method of the function reference passed to module.provider .
Provider Function angular.module ( ' myApp ' , []) .provider( ' myPro ' , function () { console.log( ' myApp => Create provider => retrun object with $get' ); return { isTrue : false , $get: function b($ log ) { var self = this ; console.log( ' myApp => my Provider $get => retrun func ' ); return function c( msg ) { $ log.debug ( msg + " isTrue : " + self.isTrue ); }; } }; }); Step 1: Invoke the function before the config stage. No args . app.config ( function ( myProProvider ) { myProProvider.isTrue = true ; console.log( ' myApp --> config ' ); }); Step 2: This object will be available in config stage as injectable service. The name is " myPro Provider " . Step 3: $get func is a factory func for the service, invoke only if needed and only once. Available after the config stage. Step 4: The injectable service.
Provider Lifecycle Angular register your provider ( {..} | f ) Module Config ( {..} ) Execute the $get function Decorator stage Module Run( {..} | f )
Provider Service
Angular Provider Function Code function provider(name, provider_) { if ( isFunction (provider_) || isArray (provider_)) { provider_ = providerInjector.instantiate (provider_); } if (! provider_.$get ) { throw Error (... 'must define $get factory method.' ); } return providerCache [name + providerSuffix ] = provider_; } // Register an object provider myApp.provider ( 'awesome' , { $get: function () { return 'awesome data' ; } }); Step 1: Invoke the function before the config stage. No args . Step 2: This object will be available in config stage as injectable service. The name is "[name + providerSuffix ]" .
Factory Function angular.module ( ' myApp ' , []) .factory( ' myfac ' , function ($http) { console.log( ' myApp -> Create factory' ); return function ( msg ) { console.log( msg ); }; }); Step 2: The injectable service. Step 1: factory func for the service, invoke only if needed and only once. Available after the config stage. app.run ( function ( myfac ){ console.log( ' myApp --> run' ); myfac ( "test" ); });
Service Function function MyService ($http) { console.log( 'Create my Service => retrun object this.' ); this .msg = 'NAN' ; } MyService.prototype.log = function ( val ) { console.log( this .msg + val ); }; angular.module ( ' myApp ' , []). service ( ' myService ' , MyService ); Angular use the new operator to create instance. The return object ( this ) is the singleton service. Everything that uses the service will get the same instance !
Angular Service Function Code function service(name, constructor ) { return factory(name, [ '$injector' , function ($injector) { // instantiated with the new operator return $ injector.instantiate ( constructor ); }]); } Angular use the new operator to create instance. The return object ( this ) is the singleton service. Everything that uses the service will get the same instance !
Angular Service Is Provider function service(name, constructor ) { return provider (name , { $get : [ '$ injector' , function ($injector) { // instantiated with the new operator return $ injector.instantiate ( constructor ); }] } ); } Angular use the new operator to create instance. The return object ( this ) is the singleton service. Everything that uses the service will get the same instance !
Value Function function value(name, value) { return factory(name, valueFn (value)); } // Sample Code myApp.value ( 'awesome' , 'awesome data' ); function valueFn (value) { return function () { return value;};}
// Sample Code angular.module ( ' myApp ' , []) .constant( 'PI' , 3.14 ) . config ( function (PI) { ... }); Constant Function Constant differs from value in that it's accessible during config . Constant cannot be overridden by an Angular decorator. // AngularJS Constant Code function constant(name, value) { providerCache [name] = value; instanceCache [name] = value; }
Angular $provide (Custom Service)
Provider Lifecycle Angular register your provider ( {..} | f ) Module Config ( {..} ) Execute the $get function Decorator stage Module Run( {..} | f )
Decorator Function A service decorator intercepts the creation of a service, allowing it to override or modify the behavior of the service . Here we decorate the $log service to convert warnings to errors by intercepting calls to $ log.warn (). // Sample Code $ provide .decorator ( '$log' , function ($delegate, $http) { $ delegate.warn = $ delegate.error ; return $delegate; }); $log You can ask any service
Angular Decorator Code function decorator( serviceName , decorFn ) { var origProvider = providerInjector.get ( serviceName + providerSuffix ), orig$get = origProvider .$get; origProvider .$get = function () { var origInstance = instanceInjector.invoke ( orig$get , origProvider ); return instanceInjector.invoke ( decorFn , null , { $delegate: origInstance } ); }; } Override the $get function. Invoke the decoFn with original service instance as argument.
Decorator
Thanks eyalvardi.wordpress.com Eyal Vardi Microsoft MVP ASP.NET blog: eyalvardi.wordpress.com