学习angular技术 ,
疑问1 Difference between Constructor and ngOnInit
下面这个是中文版
https://blog.youkuaiyun.com/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.
本文探讨了Angular中构造函数(constructor)与初始化方法(ngOnInit)的区别。构造函数主要用于依赖注入,使注入的服务可以直接作为类的属性使用。而ngOnInit则是在构造函数之后调用,通常用于启动Angular的绑定等初始化任务。

被折叠的 条评论
为什么被折叠?



