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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s