1

In my AngularJS application I want to initialize a factory service, without calling it from a controller or other service. How can this be done?

The reason is that I want the service to call one of its functions when the application loads.

3
  • 1
    You can always load the service and its methods using the app bootstrap function run. Commented May 30, 2016 at 9:01
  • I've updated my question, think I might have explained it the wrong way ;-) Commented May 30, 2016 at 9:07
  • 1
    As said by @AranS, you can call service method during run phase of angular module. We are doing same thing for our web analytics Commented May 30, 2016 at 9:10

1 Answer 1

2

You could just inject your service in the angular.module(...).run(...) function. Then you could add the required code in the Service's main function/constructor.

But just injecting the Service without using it is a bad practice, because you or someone could remove it some day without knowing why it was injected.

So the best way to me is to inject the service in the .run function AND call a yourService.init() method that you will expose from your Service. That would be more explicit.

app.run(['yourService', function(yourService) {
  yourService.init();
}]);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.