Initialize an uninjected angular service

I have an angular service that in its constructor listens for an event on the root $ directory.

This service is not entered anywhere in the application, and therefore it is not initialized. To solve this, we simply introduce it, and do not use it in another service, just to make it "new."

Is there a way to initialize a service without inserting it into any other service / controller / directive?

+4
source share
1 answer

Typically, Angular provides an API module.run(fn)for initialization. The argument is fnfully injectable, so if you have a service, for example myService, that provides a method init(), you can initialize it as:

angular.module(...).run(['myService', function(myService) {
    myService.init();
}]);

If the service initialization code is placed in the service constructor, that is:

angular.module(...).service(function() {
    ...initialization code...
});

... then just declare the dependency on the service in your method run(), that is:

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 shorten it as shown below:

angular.module(...).run(['myService', angular.noop]);

(Sidenote: I find this template a bit inconvenient, if the service contains only the initialization code, just implement the initialization code directly in the function run(). In any case, you can attach the mulitple functions run()to each module.)

+3
source

All Articles