stack shalini
stack shalini

Reputation: 117

Why is it not a good practice to write initialization logic in the constructor in angular 2

Why do we write initialization logic only in the OnInit() method and not in constructor method? What are all the side effects of using constructor method for initialization? Please explain.

Upvotes: 3

Views: 2587

Answers (2)

Reactgular
Reactgular

Reputation: 54821

An unhandled error in the constructor will escape the call stack, and force the stack frame to jump up the call stack to the first error handler. Any parent components that are still being constructed that are on the current call stack will also be crashed.

@Component({..})
export class ExampleComponent implements OnDestroy {
   public constructor() {
      throw new Error("I crash the app!");
   }

   public ngOnDestroy() {
      console.error('I am never executed!');
   }
}

The OnInit() method happens inside the digest cycle of the Angular render loop, and is called independently from the parent component. An unhandled error here will only escape the digest of the current component, and parent components will continue to work without interruption.

@Component({..})
export class ExampleComponent implements OnInit, OnDestroy {
   public ngOnInit() {
      throw new Error("I crash gracefully!");
   }

   public ngOnDestroy() {
      console.log('I am still executed!');
   }
}

Where errors happen has an impact on the life cycle of the component. The ngOnDestroy method will continue to work if an error happens in ngOnInit, but the component is completely lost if the error happens in the constructor.

Upvotes: 8

Steve
Steve

Reputation: 1953

From the Angular docs (found here):

Use ngOnInit() for two main reasons:

To perform complex initializations shortly after construction. To set up the component after Angular sets the input properties. Experienced developers agree that components should be cheap and safe to construct.

Don't fetch data in a component constructor. You shouldn't worry that a new component will try to contact a remote server when created under test or before you decide to display it. Constructors should do no more than set the initial local variables to simple values.

An ngOnInit() is a good place for a component to fetch its initial data.

An article by Mike Hevery (Angular team lead) says more here

The constructor is used to create the class while the onInit is used to build the component itself. Although I have never experienced this myself, apparently it is possible for resources to not be fully available in the constructor

This article, although a bit simplistic, has more to say but is not official Angular documentation

From my experience, although I keep constructor code to a minimum, I have never had an issue with code failing to run or causing issues because it is in the constructor and not the onInit method.

Upvotes: 4

Related Questions