Developer Guide: Angular Services: Managing Service Dependencies

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 via the $inject property, as an array of string identifiers. Optionally the $inject property declaration can be dropped (see "Inferring $inject" but note that that is currently an experimental feature).

Here is an example of two services that depend on each other, as well as on other services that are provided by angular's web 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.
*/
angular.service('batchLog', function($defer, $log) {
  var messageQueue = [];

  function log() {
    if (messageQueue.length) {
      $log('batchLog messages: ', messageQueue);
      messageQueue = [];
    }
    $defer(log, 50000);
  }

  // start periodic checking
  log();

  return function(message) {
    messageQueue.push(message);
  }
}, {$inject: ['$defer', '$log']});
// note how we declared dependency on built-in $defer and $log services above

/**
* routeTemplateMonitor monitors each $route change and logs the current
* template via the batchLog service.
*/
angular.service('routeTemplateMonitor', function($route, batchLog) {
  this.$on('$afterRouteChange', function() {
    batchLog($route.current ? $route.current.template : null);
  });
}, {$inject: ['$route', 'batchLog'], $eager: true});

Things to notice in this example:

Related Topics

Related API