欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解Angular之constructor和ngOnInit差異及適用場(chǎng)景

 更新時(shí)間:2017年06月22日 14:32:27   作者:劉文壯  
這篇文章主要介紹了詳解Angular之constructor和ngOnInit差異及適用場(chǎng)景的相關(guān)資料,有興趣的可以了解一下

Angular中根據(jù)適用場(chǎng)景定義了很多生命周期函數(shù),其本質(zhì)上是事件的響應(yīng)函數(shù),其中最常用的就是ngOnInit。但在TypeScript或ES6中還存在著名為constructor的構(gòu)造函數(shù),開(kāi)發(fā)過(guò)程中經(jīng)常會(huì)混淆二者,畢竟它們的含義有某些重復(fù)部分,那ngOnInit和constructor之間有什么區(qū)別呢?它們各自的適用場(chǎng)景又是什么呢?

區(qū)別

constructor是ES6引入類(lèi)的概念后新出現(xiàn)的東東,是類(lèi)的自身屬性,并不屬于A(yíng)ngular的范疇,所以Angular沒(méi)有辦法控制constructor。constructor會(huì)在類(lèi)生成實(shí)例時(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無(wú)關(guān)');
  }
}

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

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

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

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

ngOnInit屬于A(yíng)ngular生命周期的一部分,其在第一輪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適用場(chǎng)景

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

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

@Component({
  selector: 'hello-world',
  templateUrl: 'hello-world.html'
})
class HelloWorld {
  constructor(private elementRef: ElementRef) {
    // 在類(lèi)中就可以使用this.elementRef了
  }
}

constructor中注入的依賴(lài),就可以作為類(lèi)的屬性被使用了。

ngOnInit適用場(chǎng)景

ngOnInit純粹是通知開(kāi)發(fā)者組件/指令已經(jīng)被初始化完成了,此時(shí)組件/指令上的屬性綁定操作以及輸入操作已經(jīng)完成,也就是說(shuō)在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中做一些初始化操作。

總結(jié)

開(kāi)發(fā)中我們經(jīng)常在ngOnInit做一些初始化的工作,而這些工作盡量要避免在constructor中進(jìn)行,constructor中應(yīng)該只進(jìn)行依賴(lài)注入而不是進(jìn)行真正的業(yè)務(wù)操作。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論