4

I have a service:

angular.module('USC').service('TemplateService', function() {});

That I would like to use before I manually bootstrap my Angular project:

angular.bootstrap(document, ['USC']);

Is this possible? I know I can call var service = angular.bootstrap().get(); for Angular provided services, but how would I call a custom one before the module was initialized?

2
  • Do you want it to be the same service instance that your app will use once bootstraped orr could it be a different instance ? Commented May 19, 2014 at 19:46
  • @ExpertSystem it would be ideal to be the same service instance, however if it could only be a different instance that is fine, since technically the app has not bootstrapped yet. Commented May 19, 2014 at 20:03

1 Answer 1

9

If it is OK to have a different instance of the service than the one that will be used by the app itself, you can achieve what you want like this:

angular.injector(['ng', 'yourApp']).get('SomeService').doStuff();

See, also, this short demo.
As you can see the service is re-instantiated (so counter starts from 0) for use within the Angular app.

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

3 Comments

Thanks, yes to me it makes sense to have it re-instantiated as there is not instance of the app itself yet.
If you want to use the same instance of your service after the bootstrap you can set as a yourApp.constant('SomeService', SomeService);
Thanks for this tip! In case anyone else also has a "yourApp" which has dependencies, ie angular.module('yourApp', ['yourApp.services']), and need this technique to load some JSON config file, you can define the other service to inject in a different module all toegether, like angular.module('preboostrappStuff',[]). Thanks @ExpertSystem, your demo was what I needed!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.