angular - ngOnInit vs constructor in Angular
问题描述
ngOnInit: Invoked by Angular when component is initialized
constructor: Constructor is automatically called at the time of creating object of the class
How do we know when component is initialized? Which function is responsible for this?
ngOnInit: Everything is ready at the time of invocation.
constructor: Not everything in component is initialized at the time of invocation
What is "everything" that is ready at the time of invocation?
https://angular.io/api/core/OnInit
A callback method that is invoked immediately after the default change detector has checked the directive's data-bound properties for the first time, and before any of the view or content children have been checked. It is invoked only once when the directive is instantiated.
Also, please explain the bold lines in the above quote.
解决方案
Here is the exection order of various functions during the lifecycle of a component
- constructor
- OnChanges
- OnInit
- DoCheck
- AfterContentInit
- AfterContentChecked
- AfterViewInit
- AfterViewChecked
- OnDestroy
So by the time the constructor is called the change detection has not yet completed and some of the variables might not be initialized (for eg. input variables with @Input()
decorator). However by the time ngOnInit()
is hit, the component has been properly initialized.
推荐阅读
- acumatica - Acumatica:如何使用 REST API 覆盖销售订单中的 Bill-To Address 和 Ship-To Address
- javascript - 在反应css中使悬停弹出窗口不透明
- javascript - 如何处理“承诺{
}”在 JavaScript 中 - reactjs - React 中 PDF 的放大镜效果
- php - 在 ocmod opencart v2 中找不到错误代码
- php - 将 symfony 会话数据存储在两个不同的会话存储中
- python - 加载静态文件时 Amazon S3 出现 403 错误
- c++ - 编译 LLVM 期间链接文件时出错
- c# - Botframework Composer 自定义操作未在工厂注册
- zapier - 您如何创建和添加 Zapier Zap 操作链接?