5

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?

2
  • 2
    Use module.run() for initializations; if you want to encapsulate the logic in a service, have run() depend on that service and invoke an init() function (or just use the constructor as you did). Commented Feb 5, 2015 at 12:19
  • Thank you! Worked fine! If you put it in an answer I can accept it! I did not quite understand how I would make run() dependent on my service. I just gave it a function pointer that had a $inject property. Commented Feb 5, 2015 at 13:19

1 Answer 1

4

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

Alright, I will just provide the initialization-function. There is no longer a need for it to be a service i guess.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.