In Angular 7, if we have a service declared as @Injectable({providedIn: 'root'}), when does it's constructor execute? Does it execute upon the construction of a component that uses it (as a dependency) or does it wait until a method in that service is first called?
Note: Since the service is a singleton, I use the service's constructor to initialize some values. I could create a "Initialize()" method and call that in the component's constructor instead but I find this aproach a little messy.
OnInit : ngOnInit is component's life cycle hook which runs first after constructor(default method) when the component is being initialized. So, Your constructor will be called first and Oninit will be called later after constructor method.
Constructor in Angular is put into use to inject dependencies into the component class. It creates a new instance of the class when the compiler calls 'new MyClass ()'. While calling 'new MyClass()', it is vital that the exact match of the parameter passes the Angular component constructor of the class.
The @Injectable() decorator defines a class as a service in Angular and allows Angular to inject it into a component as a dependency. Likewise, the @Injectable() decorator indicates that a component, class, pipe, or NgModule has a dependency on a service. The injector is the main mechanism.
Dependency injection (DI) is a paradigm. The way it works in Angular is through a hierarchy of injectors. A class receives its resources without having to create or know about them. Injectors receive instruction and instantiate a service depending on which one was requested.
Instances of injected services are created at the point a component that requires them is first created or when another service that requires them is first instantiated.
When a component (or another service) that requires a Service as a dependency is created (or instantiated), Angular scans the Dependency Injection tree, and looks for a definition (and an instance of the injected service). If no instance of the injected service is found, Angular creates an instance of the injected service, and only then does its constructor run.
Another way to instantiate a service before an object (or another service) that require it are created, is to add it as a dependency to the APP_INITIALIZER
in the deps
array, like this:
{ provide: APP_INITIALIZER, useFactory: () => () => null, deps: [MyService], multi: true }
This will create an instance of MyService
when the app is initialized regardless of when other components/services that require it are created.
More details here.
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