0

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.

Ankita Prasad
  • 57
  • 1
  • 9
  • F.ex. if you will extend a class later, child class can call `super()` to call base class constructor to pass the dependencies – Julius Dzidzevičius Feb 11 '21 at 18:16
  • Okay, and why component constructor is the only place where we declare dependencies? – Ankita Prasad Feb 11 '21 at 18:55
  • I am not too confident to detail how ES6 works, but imagine simple case - you have a class `class Car { name; constructor(brand) { this.brand = brand }` When you initialise this class you call - `new Car('Porche')`. If you were to initialise dependency somewhere else, this wouldnt work – Julius Dzidzevičius Feb 11 '21 at 18:59
  • okay, getting your point. This might be a reason. – Ankita Prasad Feb 11 '21 at 19:21
  • Remember that defining the dependencies as parameters with public or private keywords in the constructor is a typescript shortcut as explained in this post: https://dev.to/satansdeer/typescript-constructor-shorthand-3ibd - Angular DI uses this as an idiom. – Dani P. Feb 11 '21 at 21:09

1 Answers1

1

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

Dani P.
  • 1,073
  • 1
  • 10
  • 28