Search code examples
angularconstructorngoninit

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.


Solution

  • 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.