new MyClass(someArg);
ngOnInit是一个由Angular2调用的生命周期钩子,用于指示Angular是创建组件的。
我们必须导入OnInit为了像这样使用(实际上实现OnInit不是强制性的,但被认为是良好的做法):
import {Component,OnInit} from 'angular2/core';
然后使用OnInit的方法,我们必须在类中实现这样。
export class App implements OnInit{
constructor(){
//called first time before the ngOnInit()
}
ngOnInit(){
//called after the constructor and called after the first ngOnChanges()
}
}
Implement this interface to execute custom initialization logic after your directive’s data-bound properties have been initialized.
ngOnInit is called right after the directive’s data-bound properties have been checked for the first time,
and before any of its children have been checked.
It is invoked only once when the directive is instantiated.
大多数情况下,我们使用ngOnInit来初始化/减速,避免在构造函数中工作。构造函数应该只用于初始化类成员,但不应该做实际的“工作”。
所以你应该使用constructor()来设置依赖注入,而不是其他的。 ngOnInit()是“start”的更好的地方 – 它是在哪里/当组件的绑定被解决
更多信息请参考这里
> https://angular.io/docs/js/latest/api/core/index/OnInit-class.html
> Angular 2 Component Constructor Vs OnInit