Ron Avraham
Ron Avraham

Reputation: 478

Angular 2 service startup

Is it possible to execute a service in angular 2 at startup? bootstrap does not execute the service's contstructor. And also, the injector is executing the service's contstructor each time there is an injection of the service in some component. is there a way to make the service singelton and make sure the ctor will run only once?

Upvotes: 4

Views: 1996

Answers (2)

jeff
jeff

Reputation: 3327

Bootstrap won't start the service, a consuming class that is injecting the service will. By listing it in bootstrap you will get singleton.

If you follow the convention of listing your injectable services (LogRepository) into the bootstrap, then all services will be singleton. (As in LogRepository) bootstrap(TheApp, [HTTP_PROVIDERS,LogRepository]);

You can get more instances of injectable services if you list them as providers on a component but starting out, just list them in the bootstrap(). All singleton then.

Upvotes: 1

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657118

Add the service only to bootstrap and not to proiders in your components. If you inject it in your AppComponent it will be instantiated and only once.

Adding the service to providers on a component creates a new instance for each component instance.

Upvotes: 2

Related Questions