gpt4 book ai didi

angular - 构造函数和 ngOnInit 之间的区别

转载 作者:太空狗 更新时间:2023-10-29 16:43:58 25 4
gpt4 key购买 nike

Angular默认提供生命周期钩子(Hook)ngOnInit

如果我们已经有了构造函数,为什么还要使用ngOnInit

最佳答案

Constructor 是类的默认方法,在实例化类时执行,并确保正确初始化类及其子类中的字段。 Angular 或更好的依赖注入(inject)器 (DI) 分析构造函数参数,当它通过调用 new MyClass() 创建新实例时,它会尝试找到与构造函数参数类型匹配的提供程序,解析它们并将它们传递给构造函数,例如

new MyClass(someArg);

ngOnInit 是 Angular 调用的生命周期钩子(Hook),用于指示 Angular 已完成创建组件。

我们必须像这样导入 OnInit 才能使用它(实际上实现 OnInit 不是强制性的,但被认为是好的做法):

import { Component, OnInit } from '@angular/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() 来设置依赖注入(inject)而不是其他。 ngOnInit() 是更好的“开始”位置 - 它是解析组件绑定(bind)的位置/时间。

更多信息请引用这里:

重要的是要注意 @Input 值在构造函数中不可访问(感谢@tim 在评论中提出建议)

关于angular - 构造函数和 ngOnInit 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35763730/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com