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?
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.
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.
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).
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.
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}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With