溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Angular之constructor和ngOnInit差異有哪些

發(fā)布時間:2021-08-17 13:44:24 來源:億速云 閱讀:137 作者:小新 欄目:web開發(fā)

小編給大家分享一下Angular之constructor和ngOnInit差異有哪些,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

區(qū)別

constructor是ES6引入類的概念后新出現(xiàn)的東東,是類的自身屬性,并不屬于Angular的范疇,所以Angular沒有辦法控制constructor。constructor會在類生成實(shí)例時調(diào)用:

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

@Component({
  selector: 'hello-world',
  templateUrl: 'hello-world.html'
})

class HelloWorld {
  constructor() {
    console.log('constructor被調(diào)用,但和Angular無關(guān)');
  }
}

// 生成類實(shí)例,此時會調(diào)用constructor
new HelloWorld();

既然Angular無法控制constructor,那么ngOnInit的出現(xiàn)就不足為奇了,畢竟槍把子得握在自己手里才安全。

ngOnInit的作用根據(jù)官方的說法:

ngOnInit用于在Angular第一次顯示數(shù)據(jù)綁定和設(shè)置指令/組件的輸入屬性之后,初始化指令/組件。

ngOnInit屬于Angular生命周期的一部分,其在第一輪ngOnChanges完成之后調(diào)用,并且只調(diào)用一次:

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

@Component({
  selector: 'hello-world',
  templateUrl: 'hello-world.html'
})

class HelloWorld implements OnInit {
  constructor() {

  }

  ngOnInit() {
    console.log('ngOnInit被Angular調(diào)用');
  }
}

constructor適用場景

即使Angular定義了ngOnInit,constructor也有其用武之地,其主要作用是注入依賴,特別是在TypeScript開發(fā)Angular工程時,經(jīng)常會遇到類似下面的代碼:

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純粹是通知開發(fā)者組件/指令已經(jīng)被初始化完成了,此時組件/指令上的屬性綁定操作以及輸入操作已經(jīng)完成,也就是說在ngOnInit函數(shù)中我們已經(jīng)能夠操作組件/指令中被傳入的數(shù)據(jù)了:

// 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中還不能獲取到組件/指令中被傳入的數(shù)據(jù)
    console.log(this.name);   // undefined
  }

  ngOnInit() {
    // ngOnInit中已經(jīng)能夠獲取到組件/指令中被傳入的數(shù)據(jù)
    console.log(this.name);   // 傳入的數(shù)據(jù)
  }
}

所以我們可以在ngOnInit中做一些初始化操作。

看完了這篇文章,相信你對“Angular之constructor和ngOnInit差異有哪些”有了一定的了解,如果想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI