Reputation: 3576
I have a angular service that in its constructor listens to an event on the $rootscope.
This service is not injected anywhere in the application and therefore it is not initialized. To solve that we're just injecting it and not using it in another service, just to get it to be "newd up".
Is there some way to initialize a service without having to inject it in some other service/controller/directive?
Upvotes: 5
Views: 2183
Reputation: 40298
Generally, Angular gives you the module.run(fn)
API to do initializations. The fn
argument is fully injectable, so if you have a service, e.g. myService
, that exposes an init()
method, you can initialize it as:
angular.module(...).run(['myService', function(myService) {
myService.init();
}]);
If the service initialization code is placed in the service constructor, i.e.:
angular.module(...).service(function() {
...initialization code...
});
...then it is enough to just declare the dependency on the service in your run()
method, i.e.:
angular.module(...).run(['myService', function() {
// nothing else needed; the `myService` constructor, containing the
// initialization code, will already have run at this point
}]);
In fact, you can abbreviate it as below:
angular.module(...).run(['myService', angular.noop]);
(Sidenote: I find this pattern a bit awkward; if a service contains only initialization code, just implement the initialization code directly in a run()
function. You can attach mulitple run()
functions to each module anyway.)
Upvotes: 4