angular allows the service to declare other services as dependencies, using the constructor used when instantiating itself.
To declare dependencies, we need to specify them in the factory method declaration and use the $inject attribute (string identification array) or use array notation in the factory method.
Usually the $inject property declaration can be discarded (i.e. the implicit dependency injection mentioned in //www.VeVB.COM/article/91815.htm, but this is an experimental property and will fail after compression and obfuscation, please use it with caution!).
Use array notation
function myModuleCfgFn ($provide) { $provide.factory('myService',['dep1','dep2',function(dep1,dep2){}]);}Use the $inject property
function myModuleCfgFn($provide) { var myServiceFactory = function(dep1, dep2) {}; myServiceFactory.$inject = ['dep1', 'dep2']; $provide.factory('myService', myServiceFactory); }Using Implicit DI (incompatible with compression obfuscated code)
function myModuleCfgFn($provide) { $provide.factory('myService', function(dep1, dep2) {});}Here is an example where there are two services, and there are dependencies between them, as well as some other services provided by angular.
/** * batchLog service allows messages to form a queue in memory, flushing once 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); } log(); return function(message) { messageQueue.push(message); } }]); /** * routeTemplateMonitor monitors the changes of each route, and each Bi'anu will record it through 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, run the application (listen to the event) angular.injector([batchLogModule]).get('routeTemplateMonitor');Things to note in the example:
The above is the compilation of AngularJs Managing Service Dependencies information. We will continue to add relevant information in the future. Thank you for your support for this website!