构造函数和 ngOnInit 之间的区别 [英] Difference between Constructor and ngOnInit

查看:38
本文介绍了构造函数和 ngOnInit 之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angular 默认提供生命周期钩子ngOnInit.

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

解决方案

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

new MyClass(someArg);

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

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

import { Component, OnInit } from '@angular/core';

然后为了使用OnInit方法,我们必须实现这样的类:

export class App 实现 OnInit {构造函数(){//在 ngOnInit() 之前第一次调用}ngOnInit() {//在构造函数之后调用并在第一个 ngOnChanges() 之后调用}}

<块引用>

实现此接口以在您的指令的数据绑定属性初始化后执行自定义初始化逻辑.在第一次检查指令的数据绑定属性后立即调用 ngOnInit,在它的任何孩子被检查之前.仅在指令实例化时调用一次.

大多数情况下,我们使用 ngOnInit 进行所有初始化/声明,并避免在构造函数中工作.构造函数应该只用于初始化类成员,而不应该做实际的工作".

所以你应该使用 constructor() 来设置依赖注入而不是其他的.ngOnInit() 是更好的开始"位置——它是解决组件绑定的地方/时间.

有关更多信息,请参阅此处:

Angular provides life cycle hook ngOnInit by default.

Why should ngOnInit be used, if we already have a constructor?

解决方案

The Constructor is a default method of the class that is executed when the class is instantiated and ensures proper initialisation of fields in the class and its subclasses. Angular, or better Dependency Injector (DI), analyses the constructor parameters and when it creates a new instance by calling new MyClass() it tries to find providers that match the types of the constructor parameters, resolves them and passes them to the constructor like

new MyClass(someArg);

ngOnInit is a life cycle hook called by Angular to indicate that Angular is done creating the component.

We have to import OnInit like this in order to use it (actually implementing OnInit is not mandatory but considered good practice):

import { Component, OnInit } from '@angular/core';

then to make use of the method OnInit, we have to implement the class like this:

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.

Mostly we use ngOnInit for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn't do actual "work".

So you should use constructor() to setup Dependency Injection and not much else. ngOnInit() is better place to "start" - it's where/when components' bindings are resolved.

For more information refer here:

这篇关于构造函数和 ngOnInit 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆