Angular 2 Lifecycle Hooks

Lifecycle Hooks Angular 2 docs

(From halfway down the page) We turn to ngOnInit for two main reasons:

  1. To perform complex initializations shortly after construction
  2. To set up the component after Angular sets the input properties

HTTP client – oninit Angular 2 docs

Although at runtime the component requests heroes immediately after creation, we do not call the service’s getmethod in the component’s constructor. We call it inside the ngOnInit lifecycle hook instead and count on Angular to call ngOnInit when it instantiates this component.

This is a best practice. Components are easier to test and debug when their constructors are simple and all real work (especially calling a remote server) is handled in a separate method.

Advertisements