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.https:///article/Implicit dependency injection mentioned in this, but this is an experimental attribute, and it will fail after compression and obfuscation. Use it with caution! ).
Use array notation
function myModuleCfgFn ($provide) { $(‘myService',[‘dep1','dep2',function(dep1,dep2){}]); }
Use the $inject property
function myModuleCfgFn($provide) { var myServiceFactory = function(dep1, dep2) {}; myServiceFactory.$inject = ['dep1', 'dep2']; $('myService', myServiceFactory); }
Using Implicit DI (incompatible with compression obfuscated code)
function myModuleCfgFn($provide) { $('myService', function(dep1, dep2) {}); }
There is an example below, which contains 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){ $('batchLog', ['$timeout', '$log', function($timeout, $log) { var messageQueue = []; function log() { if () { $log('batchLog messages: ', messageQueue); messageQueue = []; } $timeout(log, 50000); } log(); return function(message) { (message); } }]); /** * routeTemplateMonitor monitors the changes of each route, and every Bi'anu will record it through batchLog service */ $('routeTemplateMonitor', ['$route', 'batchLog', '$rootScope', function($route, batchLog, $rootScope) { $rootScope.$on('$routeChangeSuccess', function() { batchLog($ ? $ : null); }); }]); } // Get the main service and run the application (listen to events)([batchLogModule]).get('routeTemplateMonitor');
Things to note in the example:
- batchLog service relies on the built-in $timeout(/api/ng.$timeout) and $log services(/api/ng.$log) of angular to realize batch log messages.
- routeTemplateMonitor service depends on the built-in $route (/api/ng.$route) service with our custom batchLog service.
- Both of our services use factory method signatures and array notation to annotate injects and declare their dependencies. It is important that the order of string identification in an array must be consistent with that in the factory method signature (parameter). Unless an implicit dependency declaration is used in the factory method parameters, the injector will decide which service inject is based on the order of strings in the array.
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!