Angular dependency injection and data initialization

1.4k Views Asked by At

I have a conceptual doubt that why do we use the constructor for injecting our services into the component and ngOnInit() life cycle hook to initialize all values. Of all the articles I've read, I understood that it's good practice to initialize values in ngOnInit() as all dependencies would have been available at that point. In practice, I've seen that initializing in constructor also works fine apart from that.

Regarding injecting services in the constructor, I came across these lines

When Angular constructs a components tree the root module injector is already configured so you can inject any global dependencies. Also, when Angular instantiates a child component class the injector for the parent component is also already set up so you can inject providers defined on the parent component including the parent component itself. A component constructor is the only method that is called in the context of the injector so if you need any dependency that’s the only place to get those dependencies.

However, I'm not able to gauge why exactly it is a good place. It'll be a great help if someone can help me out with understanding this core usage.

1

There are 1 best solutions below

0
On

In the component constructor you will have all your dependencies injected, so you can use your services or other tokens there safely.

Theres is a long debate on initializing subscriptions in constructor or ngOnInit() but most of cases it just a matter of taste or style.

The only thing that you have to take into account is that in the constructor you don't have any @Input values available, they will be in the ngOnInit().

If you extend your components just make sure that you call super() or super.ngOnInit().

Try to always leverage Angular DI instead of manual creating services or providing dependencies to avoid pitfalls.

See docs: https://angular.io/guide/dependency-injection https://angular.io/guide/lifecycle-hooks