国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

詳解Angular之constructor和ngOnInit差異及適用場景

2024-05-06 15:15:34
字體:
來源:轉載
供稿:網友

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無關');  }}// 生成類實例,此時會調用constructornew 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.tsimport { 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);   // 傳入的數據  }}            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 互助| 虎林市| 铅山县| 自贡市| 景东| 武陟县| 搜索| 三门县| 团风县| 新和县| 满城县| 明水县| 富阳市| 阿拉善左旗| 黎平县| 洛扎县| 贵定县| 额尔古纳市| 万载县| 阳高县| 德兴市| 大厂| 焦作市| 临泽县| 许昌县| 侯马市| 崇义县| 博白县| 德钦县| 安吉县| 西城区| 天祝| 康平县| 西乌珠穆沁旗| 田东县| 海门市| 普洱| 东丽区| 吉木萨尔县| 商水县| 东宁县|