原始地址:https://blog.csdn.net/u010730126/article/details/64486997html
Angular中根据适用场景定义了不少生命周期函数,其本质上是事件的响应函数,其中最经常使用的就是ngOnInit。但在TypeScript或ES6中还存在着名为constructor的构造函数,开发过程当中常常会混淆两者,毕竟它们的含义有某些重复部分,那ngOnInit和constructor之间有什么区别呢?它们各自的适用场景又是什么呢?安全
区别
constructor是ES6引入类的概念后新出现的东东,是类的自身属性,并不属于Angular的范畴,因此Angular没有办法控制constructor。constructor会在类生成实例时调用:函数
import {Component} from '@angular/core';this
@Component({
selector: 'hello-world',
templateUrl: 'hello-world.html'
}).net
class HelloWorld {
constructor() {
console.log('constructor被调用,但和Angular无关');
}
}htm
// 生成类实例,此时会调用constructor
new HelloWorld();blog
// 生成类实例,此时会调用constructor
new HelloWorld();
既然Angular没法控制constructor,那么ngOnInit的出现就不足为奇了,毕竟枪把子得握在本身手里才安全。生命周期
ngOnInit的做用根据官方的说法:事件
ngOnInit用于在Angular第一次显示数据绑定和设置指令/组件的输入属性以后,初始化指令/组件。ip
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中应该只进行依赖注入而不是进行真正的业务操做。--------------------- 做者:刘文壮 来源:CSDN 原文:https://blog.csdn.net/u010730126/article/details/64486997 版权声明:本文为博主原创文章,转载请附上博文连接!