Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Instantiate service on startup in Angular2

Tags:

angular

I hava a (singleton) service that contains some code in the constructor which should be run directly after startup. That menas an instance has to be created immidiately when the app is loaded.

One possibility to instanciate the service is to put it in the constructor of the app component:

export class AppComponent {

  constructor(private mySercive: MyService
...

but since I never use myService in this component I will get a warning like mySerive is not used and someone else in my team might delete the service. Is there a way to instanciate the serivce inside the app module?

like image 487
MarcS82 Avatar asked Jan 12 '17 13:01

MarcS82


People also ask

How do I initialize a startup service?

If you want to initialize a service before the application starts, you need to pass an instance of the service to the factory function, via the deps property of the APP_INITIALIZER provider. Next, create a factory function that will use this service.

Can we use service without injectable?

No. The @Injectable() decorator is not strictly required if the class has other Angular decorators on it or does not have any dependencies. But the important thing here is any class that is going to be injected with Angular is decorated.

What are services in angular2?

Services in Angular 2 are JavaScript functions, which are responsible for performing a single task. Services may have their associated properties and the methods, which can be included in the component. Services are injected, using DI (Dependency Injection).

Can we create multiple instances of service in Angular?

It will create multiple instances of a service. Every time a new instance of provided service will be created when a component is used inside another component.


1 Answers

You can provide a dummy APP_INITIALIZER and pass it as dependency like

@NgModule({
  providers: [{provide: APP_INITIALIZER, useMulti: true, deps: [MyService], useFactory: (myService) => null}]
like image 148
Günter Zöchbauer Avatar answered Oct 12 '22 00:10

Günter Zöchbauer