学习angular技术 ,
疑问1 Difference between Constructor and ngOnInit
下面这个是中文版
https://blog.csdn.net/u010730126/article/details/64486997
即使Angular定义了ngOnInit
,constructor
也有其用武之地,其主要作用是注入依赖,特别是在TypeScript开发Angular工程时,
在constructor
中注入的依赖,就可以作为类的属性被使用了。
如果使用了@Component 注解那么 在构造函数中不能和java 似的,注入属性,为什么,请看上一篇 关于 string 的博客,其实我没真正理解。 这也许是angular 强制这么干的,让construct的功能简单唯一。
Constructor is predefined default method of the typescript class. There is no relation between Angular and constructor
. Normally we use constructor
to define/initialize some variables, but when we have tasks related to Angular's bindings we move to Angular's ngOnInit
life cycle hook. ngOnInit
is called just after the constructor call. We can also do the same work in the constructor but its preferable to use ngOnInit
to start Angular's binding.