Difference between Constructor and ngOnInit

本文详细解释了Angular中构造函数(Constructor)的作用及其实现方式,同时对比了构造函数与OnInit生命周期钩子的区别,并介绍了OnInit的使用场景及推荐实践。

The Constructor is a default method of the class that is executed when the class is instantiated and ensures proper initialization of fields in the class and its subclasses. Angular or better Dependency Injector (DI) analyzes 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 Angular2 to indicate that Angular is done creating the component.

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

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

then to use the method of OnInit we have to implement in 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:

转载于:https://my.oschina.net/u/2275100/blog/1819360

### Angular 构造函数与 ngOnInit 生命周期钩子的区别 #### 构造函数的作用 构造函数主要用于依赖注入。当组件实例化时,Angular 使用反射机制调用类的构造函数并传入所需的依赖项。这使得开发者可以在创建对象的同时获取所需的服务和其他依赖资源[^3]。 ```typescript import { Component } from '@angular/core'; import { SomeService } from './some.service'; @Component({ selector: 'app-example', template: `<div></div>` }) export class ExampleComponent { constructor(private someService: SomeService) {} } ``` #### ngOnInit 的作用 `ngOnInit` 是 Angular 组件生命周期中的一个重要阶段,在此期间可以执行初始化逻辑。它会在第一次检测变更之前被调用一次,并且此时所有的输入属性都已经设置完毕。因此适合用于处理那些需要等待数据绑定完成的任务,比如订阅 Observable 或者发起 HTTP 请求等操作[^1]。 ```typescript import { Component, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Component({ selector: 'app-data-fetcher', templateUrl: './data-fetcher.component.html' }) export class DataFetcherComponent implements OnInit { data: any; constructor(private http: HttpClient) {} ngOnInit(): void { this.http.get('/api/data').subscribe(response => { this.data = response; }); } } ``` 通过上述对比可以看出: - **时机不同**:构造器是在组件实例刚创建的时候立即运行;而 `ngOnInit` 则稍晚一些,在首次渲染前触发。 - **用途差异**:前者主要负责依赖注入和服务配置工作;后者则更适合用来做更复杂的业务逻辑准备以及与其他服务交互的工作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值