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?

Darren
  • 10,631
  • 8
  • 42
  • 64
  • Do you want it to be the same service instance that your app will use once bootstraped orr could it be a different instance ? – gkalpak May 19 '14 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. – Darren May 19 '14 at 20:03

1 Answers1

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.

gkalpak
  • 47,844
  • 8
  • 105
  • 118
  • Thanks, yes to me it makes sense to have it re-instantiated as there is not instance of the app itself yet. – Darren May 19 '14 at 21:00
  • 2
    If you want to use the same instance of your service after the bootstrap you can set as a yourApp.constant('SomeService', SomeService); – mauricio Jul 26 '16 at 06:59
  • 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! – chwagssd Oct 07 '16 at 16:34