Angular之constructor和ngOnInit差別及適用場景(轉)

原始地址:https://blog.csdn.net/u010730126/article/details/64486997html

Angular中根據適用場景定義了不少生命週期函數,其本質上是事件的響應函數,其中最經常使用的就是ngOnInit。但在TypeScript或ES6中還存在着名爲constructor的構造函數,開發過程當中常常會混淆兩者,畢竟它們的含義有某些重複部分,那ngOnInit和constructor之間有什麼區別呢?它們各自的適用場景又是什麼呢?安全

區別
constructor是ES6引入類的概念後新出現的東東,是類的自身屬性,並不屬於Angular的範疇,因此Angular沒有辦法控制constructor。constructor會在類生成實例時調用:函數

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

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

class HelloWorld {
constructor() {
console.log('constructor被調用,但和Angular無關');
}
}htm

// 生成類實例,此時會調用constructor
new HelloWorld();blog

// 生成類實例,此時會調用constructor
new HelloWorld();

既然Angular沒法控制constructor,那麼ngOnInit的出現就不足爲奇了,畢竟槍把子得握在本身手裏才安全。生命週期

ngOnInit的做用根據官方的說法:事件

ngOnInit用於在Angular第一次顯示數據綁定和設置指令/組件的輸入屬性以後,初始化指令/組件。ip

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

總結開發中咱們常常在ngOnInit作一些初始化的工做,而這些工做盡可能要避免在constructor中進行,constructor中應該只進行依賴注入而不是進行真正的業務操做。--------------------- 做者:劉文壯 來源:CSDN 原文:https://blog.csdn.net/u010730126/article/details/64486997 版權聲明:本文爲博主原創文章,轉載請附上博文連接!

相關文章
相關標籤/搜索