Angular allows services to declare other services as dependencies needed for construction of their instances.
To declare dependencies, you specify them in the factory function signature and annotate the
function with the inject annotations either using by setting the $inject
property, as an array of
string identifiers or using the array notation. Optionally the $inject
property declaration can be
dropped (see "Inferring $inject
" but note that that is currently an experimental feature).
Using the array notation:
function myModuleCfgFn($provide) { $provide.factory('myService', ['dep1', 'dep2', function(dep1, dep2) {}]); }
Using the $inject property:
function myModuleCfgFn($provide) { var myServiceFactory = function(dep1, dep2) {}; myServiceFactory.$inject = ['dep1', 'dep2']; $provide.factory('myService', myServiceFactory); }
Using DI inference (incompatible with minifiers):
function myModuleCfgFn($provide) { $provide.factory('myService', function(dep1, dep2) {}); }
Here is an example of two services, one of which depends on the other and both of which depend on other services that are provided by the Angular framework:
/** * batchLog service allows for messages to be queued in memory and flushed * to the console.log every 50 seconds. * * @param {*} message Message to be logged. */ function batchLogModule($provide){ $provide.factory('batchLog', ['$timeout', '$log', function($timeout, $log) { var messageQueue = []; function log() { if (messageQueue.length) { $log('batchLog messages: ', messageQueue); messageQueue = []; } $timeout(log, 50000); } // start periodic checking log(); return function(message) { messageQueue.push(message); } }]); /** * routeTemplateMonitor monitors each $route change and logs the current * template via the batchLog service. */ $provide.factory('routeTemplateMonitor', ['$route', 'batchLog', '$rootScope', function($route, batchLog, $rootScope) { $rootScope.$on('$routeChangeSuccess', function() { batchLog($route.current ? $route.current.template : null); }); }]); } // get the main service to kick of the application angular.injector([batchLogModule]).get('routeTemplateMonitor');
Things to notice in this example:
batchLog
service depends on the built-in $timeout
and
$log
services, and allows messages to be logged into the
console.log
in batches.routeTemplateMonitor
service depends on the built-in $route
service as well as our custom batchLog
service.