Angular › Lifecycle Hooks
Why is the constructor generally not the right place to fetch data or perform complex setup in an Angular component?
BeginnerAnswer
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.