Advertisement
Beginner Angular, Lifecycle Hooks

Why is the constructor generally not the right place to fetch data or perform complex setup in an Angular component?

Short answer

The constructor's main job is simply setting up dependency injection, and at that point Angular has not yet fully set up the component's inputs or view.

Save Angular mock interview
Advertisement
AModel answer
The constructor's main job is simply setting up dependency injection, and at that point Angular has not yet fully set up the component's inputs or view. Fetching data or performing complex setup logic belongs in ngOnInit instead, which runs once Angular has properly initialized the component and its inputs are actually available.
// Not recommended, inputs may not be reliably set yet
constructor() {
  console.log(this.userId); // could be undefined here
}

// Correct, inputs are guaranteed to be set by this point
ngOnInit() {
  console.log(this.userId); // reliably available
}
Real-world example
A developer fixes a confusing bug where a component's data fetch used an undefined id, by moving the fetch call from the constructor into ngOnInit, where the required input value is reliably available.
Likely follow-ups
  • What kinds of things are actually appropriate to do inside a constructor in Angular?
  • How does this same guidance apply differently for signal based inputs?
Related topics