TypeScript constructor
and Angular ngOnInit
look pretty much the same, but they have differences.
1. Injecting and Consuming Service
Use constructor
for injecting dependencies into the class. This is because of the execution of constructor
always comes before ngOnInit
.
import { Injectable } from '@angular/core';
@Injectable()
export class UserService{
getUsers(): Array<any>{
return [{ name : "Chia Chong"}, { name : "Chia Chuan"},{ name : "Chia Sheng"}];
}
}
1. In this example, the UserComponent
class does not implement OnInit
. A single service is injected into the class throughconstructor
.
OnInit
)import { Component } from '@angular/core';
import { UserService } from './user.service';
@Component({
selector: 'user-app',
template: ``,
providers: [UserService]
})
export class UserComponent{
users: Array<any>;
constructor(private userService: UserService){};
}
2. Now, import OnInit
from @angular/core
, then make UserComponent
class to implement OnInit
.
In this example, the UserComponent
class consumes userService
in the ngOnInit
right after the service is injected via constructor
.
This sequence is more appropriate where a service is only be ready for consumption after the service is injected over constructor
.
OnInit
)import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';
@Component({
selector: 'user-app',
template: `
<ul>
<li *ngFor="let user of users">{{ user.name }}</li>
<ul>
`,
providers: [UserService]
})
export class UserComponent implements OnInit{
users: Array<any>;
constructor(private userService: UserService){};
ngOnInit(): void {
this.getUsers();
}
getUsers(): void {
this.users = this.userService.getUsers();
}
}
In a nut shell, wire up dependencies via construtor
, then do component initialization in ngOnInit
.
2. Resolve Binding
Another great example of constructor
vs ngOnInit
in link-Component resolve binding. The following example demonstrates, binding is resolved in ngOnInit
rather than constructor
.
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
<h1>Welcome to Angular World</h1>
<p>Hello {{name}}</p>
<app-child [pname]="name"></app-child>
`
})
export class ParentComponent {
private name: string = '';
constructor() {
this.name = 'CloudBerry';
}
}
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-child',
template: `
<p>Parent Component Name:{{pname}} </p>
`
})
export class ChildComponent implements OnInit {
@Input()
private pname: string; //parent component name
constructor() {
window.console.log('ChildComponent constructor ', this.pname); // Output:undefined
}
ngOnInit(): void {
window.console.log('ChildComponent ngOnInit ', this.pname);
}
}
ChildComponent constructor undefined
ChildComponent ngOnInit CloudBerry
References:
https://angular.io/docs/ts/latest/api/core/index/OnInit-class.html