用户登录
用户注册

分享至

详解Angular之constructor和ngOnInit差异及适用场景

  • 作者: 连云夜雨56195019
  • 来源: 51数据库
  • 2021-08-23

angular中根据适用场景定义了很多生命周期函数,其本质上是事件的响应函数,其中最常用的就是ngoninit。但在typescript或es6中还存在着名为constructor的构造函数,开发过程中经常会混淆二者,毕竟它们的含义有某些重复部分,那ngoninit和constructor之间有什么区别呢?它们各自的适用场景又是什么呢?

区别

constructor是es6引入类的概念后新出现的东东,是类的自身属性,并不属于angular的范畴,所以angular没有办法控制constructor。constructor会在类生成实例时调用:

import {component} from '@angular/core';

@component({
  selector: 'hello-world',
  templateurl: 'hello-world.html'
})

class helloworld {
  constructor() {
    console.log('constructor被调用,但和angular无关');
  }
}

// 生成类实例,此时会调用constructor
new helloworld();

既然angular无法控制constructor,那么ngoninit的出现就不足为奇了,毕竟枪把子得握在自己手里才安全。

ngoninit的作用根据官方的说法:

ngoninit用于在angular第一次显示数据绑定和设置指令/组件的输入属性之后,初始化指令/组件。

ngoninit属于angular生命周期的一部分,其在第一轮ngonchanges完成之后调用,并且只调用一次:

import {component, oninit} from '@angular/core';

@component({
  selector: 'hello-world',
  templateurl: 'hello-world.html'
})

class helloworld implements oninit {
  constructor() {

  }

  ngoninit() {
    console.log('ngoninit被angular调用');
  }
}

constructor适用场景

即使angular定义了ngoninit,constructor也有其用武之地,其主要作用是注入依赖,特别是在typescript开发angular工程时,经常会遇到类似下面的代码:

import { component, elementref } from '@angular/core';

@component({
  selector: 'hello-world',
  templateurl: 'hello-world.html'
})
class helloworld {
  constructor(private elementref: elementref) {
    // 在类中就可以使用this.elementref了
  }
}

constructor中注入的依赖,就可以作为类的属性被使用了。

ngoninit适用场景

ngoninit纯粹是通知开发者组件/指令已经被初始化完成了,此时组件/指令上的属性绑定操作以及输入操作已经完成,也就是说在ngoninit函数中我们已经能够操作组件/指令中被传入的数据了:

// hello-world.ts
import { component, input, oninit } from '@angular/core';

@component({
  selector: 'hello-world',
  template: `<p>hello {{name}}!</p>`
})
class helloworld implements oninit {
  @input()
  name: string;

  constructor() {
    // constructor中还不能获取到组件/指令中被传入的数据
    console.log(this.name);   // undefined
  }

  ngoninit() {
    // ngoninit中已经能够获取到组件/指令中被传入的数据
    console.log(this.name);   // 传入的数据
  }
}

所以我们可以在ngoninit中做一些初始化操作。

总结

开发中我们经常在ngoninit做一些初始化的工作,而这些工作尽量要避免在constructor中进行,constructor中应该只进行依赖注入而不是进行真正的业务操作。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

软件
前端设计
程序设计
Java相关