1. constructor
constructor應該是ES6中明確使用constructor來表示構造函數的,構造函數使用在class中,用來做初始化操作。當包含constructor的類被實例化時,構造函數將被調用。
來看例子:
class AppComponent {  public name: string;  constructor(name) {    console.log('Constructor initialization');    this.name = name;  }}let appCmp = new AppComponent('AppCmp');  // 這時候構造函數將被調用。console.log(appCmp.name);轉成ES5代碼如下:
var AppComponent = (function () {  function AppComponent(name) {    console.log('Constructor initialization');    this.name = name;  }  return AppComponent;  // 這里直接返回一個實例}());var appCmp = new AppComponent('AppCmp');console.log(appCmp.name);2. ngOnInit
ngOnInit是Angular中OnInit鉤子的實現。用來初始化組件。
Angular中生命周期鉤子的調用順序如下:
在Angular銷毀指令/組件之前調用。
了解了這些之后我們來看一個例子:
import { Component, OnInit } from '@angular/core';@Component({ selector: 'my-app', template: `  <h1>Welcome to Angular World</h1> `,})export class AppComponent implements OnInit { constructor() {  console.log('Constructor initialization'); } ngOnInit() {  console.log('ngOnInit hook has been called'); }}這里輸出的是:
Constructor initialization
ngOnInit hook has been called
可以看出,constructor的執行是在先的。
那么既然ngOnchanges是輸入屬性值變化的時候調用,并且ngOnInit是在ngOnchanges執行完之后才調用,而constructor是在組件就實例化的時候就已經調用了,這也就是說,在constructor中我們是取不到輸入屬性的值的。
所以還是看例子:
// parent.component.tsimport { Component } from '@angular/core';@Component({ selector: 'exe-parent', template: `  <h1>Welcome to Angular World</h1>  <p>Hello {{name}}</p>  <exe-child [pname]="name"></exe-child>  <!-- 綁定到子組件的屬性 --> `,})export class ParentComponent { name: string; constructor() {  this.name = 'God eyes'; }}// child.component.tsimport { Component, Input, OnInit } from '@angular/core';@Component({  selector: 'exe-child',  template: `   <p>父組件的名稱:{{pname}} </p>  `})export class ChildComponent implements OnInit {  @Input()  pname: string; // 父組件的輸入屬性  constructor() {    console.log('ChildComponent constructor', this.pname); // this.name=undefined  }  ngOnInit() {    console.log('ChildComponent ngOnInit', this.pname); // this.name=God eyes  }}一目了然。
3. 應用場景
看完的上面的部分可以發現,在constructor中不適合進行任何與組件通信類似的復雜操作,一般在constructor中值進行一些簡單的初始化工作:依賴注入,變量初始化等。
那么用到組件間通信的方法我們可以放在ngOnInit中去執行,比如異步請求等:
import { Component, ElementRef, OnInit } from '@angular/core';@Component({ selector: 'my-app', template: `  <h1>Welcome to Angular World</h1>  <p>Hello {{name}}</p> `,})export class AppComponent implements OnInt { name: string = ''; constructor(public elementRef: ElementRef) { // 使用構造注入的方式注入依賴對象  this.name = 'WXY';          // 執行初始化操作 } ngOnInit() {  this.gotId = this.activatedRoute.params.subscribe(params => this.articleId = params['id']); }}以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答