温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Angular之constructor和ngOnInit差异有哪些

发布时间:2021-08-17 13:44:24 来源:亿速云 阅读:132 作者:小新 栏目:web开发

小编给大家分享一下Angular之constructor和ngOnInit差异有哪些,希望大家阅读完这篇文章之后都有所收获,下面让我们一起去探讨吧!

区别

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中做一些初始化操作。

看完了这篇文章,相信你对“Angular之constructor和ngOnInit差异有哪些”有了一定的了解,如果想了解更多相关知识,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI