1.什么是變更檢測(cè)只洒?
變更檢測(cè)就是Angular檢測(cè)視圖與數(shù)據(jù)模型之間綁定的值是否發(fā)生了改變纵苛,當(dāng)檢測(cè)到模型中綁定的值發(fā)生改變時(shí)夜惭,就把數(shù)據(jù)同步到視圖上姻灶。
2.何時(shí)執(zhí)行變更檢測(cè)?
我們先看下面這個(gè)例子
import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
@Component({
selector: 'app-check-test',
templateUrl: './check-test.component.html',
styleUrls: ['./check-test.component.css']
})
export class CheckTestComponent implements OnInit {
content: string = '究竟是誰(shuí)老是觸發(fā)檢測(cè)诈茧?';
constructor(private http:HttpClient) {
}
ngOnInit() {
setTimeout(()=>{
this.changeContent();
},3000)
}
changeContent() {
this.content = '又觸發(fā)了产喉,id是:'+Math.random();
}
xmlRequest(){
this.http.get('../../assets/testcheck.json').subscribe(
(res)=>{
this.changeContent();
}
)
}
}
通過(guò)以上例子我們可以總結(jié)出來(lái),在異步事件發(fā)生的時(shí)候可能會(huì)使數(shù)據(jù)模型發(fā)生變化敢会≡颍可是angular是如何檢測(cè)到異步事件發(fā)生了呢?這還要說(shuō)起zone.js鸥昏。
- 事件:click, mouseover, keyup ...
- 定時(shí)器:setInterval塞俱、setTimeout
- Http請(qǐng)求:xmlHttpRequest
3.zone.js
官方定義zone.js是javascript的線程本地存儲(chǔ)技術(shù),猛地一聽感覺好高大上吏垮,其實(shí)zone.js就是一種用來(lái)攔截和跟蹤異步工作障涯,為JavaScript提供執(zhí)行上下文的插件。
那么它是如何感知到異步事件呢膳汪,其實(shí)方法相當(dāng)簡(jiǎn)單粗暴唯蝶,zone.js采用一種叫做猴子補(bǔ)丁 (Monkey-patched)的方式,將JavaScript中的異步任務(wù)都進(jìn)行了包裝遗嗽,這使得這些異步任務(wù)都能運(yùn)行在Zone(一個(gè)全局的對(duì)象粘我,用來(lái)配置有關(guān)如何攔截和跟蹤異步回調(diào)的規(guī)則)的執(zhí)行上下文中,每個(gè)異步任務(wù)在 Zone 中都是一個(gè)任務(wù)(Task)痹换,除了提供了一些供開發(fā)者使用的鉤子外征字,默認(rèn)情況下Zone重寫了以下方法:
- setInterval、clearInterval娇豫、setTimeout匙姜、clearTimeout
- alert、prompt冯痢、confirm
- requestAnimationFrame氮昧、cancelAnimationFrame
- addEventListener或详、removeEventListener
zone.js部分源碼
var set = 'set';
var clear = 'clear';
var blockingMethods = ['alert', 'prompt', 'confirm'];
var _global = typeof window === 'object' && window ||
typeof self === 'object' && self || global;
patchTimer(_global, set, clear, 'Timeout');
patchTimer(_global, set, clear, 'Interval');
patchTimer(_global, set, clear, 'Immediate');
patchTimer(_global, 'request', 'cancel', 'AnimationFrame');
patchTimer(_global, 'mozRequest', 'mozCancel', 'AnimationFrame');
patchTimer(_global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');
通過(guò)打印window對(duì)象我們可以發(fā)現(xiàn)zone.js對(duì)異步方法進(jìn)行了封裝,非異步方法并沒有處理郭计。
zone.js本身比較龐大復(fù)雜,這里不做深入研究椒振,對(duì)它的原理感興趣的可以看一下這篇文章-zone.js昭伸。我們這里主要是了解它是怎么配合Angular工作的即可。
在 Angular 源碼中澎迎,有一個(gè) ApplicationRef 類庐杨,其作用是當(dāng)異步事件結(jié)束的時(shí)候由 onMicrotaskEmpty執(zhí)行一個(gè) tick 方法 提示 Angular 執(zhí)行變更檢測(cè)及更新視圖。
interface ApplicationRef {
get componentTypes: Type<any>[]
get components: ComponentRef<any>[]
get isStable: Observable<boolean>
get viewCount
bootstrap<C>(componentOrFactory: ComponentFactory<C> | Type<C>, rootSelectorOrNode?: string | any): ComponentRef<C>
tick(): void
attachView(viewRef: ViewRef): void
detachView(viewRef: ViewRef): void
}
調(diào)用tick方法夹供。其中this._zone 是NgZone 的一個(gè)實(shí)例灵份, NgZone 是對(duì)zone.js的一個(gè)簡(jiǎn)單封裝。
this._zone.onMicrotaskEmpty.subscribe({
next: () => {
this._zone.run(() => { this.tick();});
}
});
tick函數(shù)對(duì)所有附在 ApplicationRef上的視圖進(jìn)行臟檢查哮洽。
tick() {
if (this._runningTick) {
throw new Error('ApplicationRef.tick is called recursively');
}
const /** @type {?} */ scope = ApplicationRef._tickScope();
try {
this._runningTick = true;
this._views.forEach((view) => view.detectChanges());
if (this._enforceNoNewChanges) {
this._views.forEach((view) => view.checkNoChanges());
}
}
catch (/** @type {?} */ e) {
// Attention: Don't rethrow as it could cancel subscriptions to Observables!
this._zone.runOutsideAngular(() => this._exceptionHandler.handleError(e));
}
finally {
this._runningTick = false;
wtfLeave(scope);
}
}
4.Angular檢測(cè)機(jī)制
Ok填渠,我們現(xiàn)在已經(jīng)知道Angular怎么監(jiān)聽異步事件了,那么當(dāng)監(jiān)測(cè)到異步事件后是怎么判斷是否需要更新視圖呢鸟辅?其實(shí)比較簡(jiǎn)單氛什,Angular通過(guò)臟檢查來(lái)判斷是否需要更新視圖。臟檢查其實(shí)就是存儲(chǔ)所有變量的值匪凉,每當(dāng)可能有變量發(fā)生變化需要檢查時(shí)枪眉,就將所有變量的舊值跟新值進(jìn)行比較,不相等就說(shuō)明檢測(cè)到變化再层,需要更新對(duì)應(yīng)視圖贸铜。當(dāng)然,實(shí)際情況肯定不是這么簡(jiǎn)單聂受,Angular會(huì)通過(guò)自己的算法來(lái)對(duì)數(shù)據(jù)進(jìn)行檢查蒿秦,對(duì)算法感興趣的可以參考這篇文章-Angular的臟檢查算法。
Angular 應(yīng)用是一個(gè)響應(yīng)系統(tǒng)饺饭,首次檢測(cè)時(shí)會(huì)檢查所有的組件渤早,其他的變化檢測(cè)則總是從根組件到子組件這樣一個(gè)從上到下的順序開始執(zhí)行,它是一棵線性的有向樹瘫俊,任何數(shù)據(jù)都是從頂部往底部流動(dòng)鹊杖,即單向數(shù)據(jù)流。怎么證明呢扛芽?看這個(gè)例子
app.component.html
<h1>變更檢測(cè)</h1>
<input type="button" value="改名" (click)="changeName()">
<app-rank-parent [parentName]="grandpaName"></app-rank-parent>
<app-refer [justRefer]="refertitle"></app-refer>
app.component.ts
import {Component, Input, OnChanges, OnInit} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnChanges {
@Input() grandpaName: string = '趙四';
refertitle:string = '僅僅是個(gè)參考組件';
constructor() {
}
ngOnInit() {
console.log('開始變更檢測(cè)啦骂蓖!');
}
ngOnChanges(changes) {
console.dir(changes);
}
changeName() {
this.grandpaName = '尼古拉斯·趙四';
this.refertitle = '你看Onpush策略下面Input屬性還有效,氣不氣人';
}
}
rank-parent.component.html
<app-rank-children [childName]="parentName"></app-rank-children>
rank-parent.component.ts
import {Component, Input, OnChanges, OnInit} from '@angular/core';
@Component({
selector: 'app-rank-parent',
templateUrl: './rank-parent.component.html',
styleUrls: ['./rank-parent.component.css']
})
export class RankParentComponent implements OnInit, OnChanges {
@Input()parentName;
constructor() {}
ngOnChanges(changes) {
console.dir(changes);
}
ngOnInit() {}
}
rank-children.component.html
<p>
兒子姓名是:{{childName}}三代
</p>
rank-children.component.ts
import {Component, Input, OnChanges, OnInit} from '@angular/core';
@Component({
selector: 'app-rank-children',
templateUrl: './rank-children.component.html',
styleUrls: ['./rank-children.component.css']
})
export class RankChildrenComponent implements OnInit,OnChanges {
@Input() childName;
constructor() { }
ngOnChanges(changes) {
console.dir(changes);
}
ngOnInit() {
}
}
運(yùn)行以后我們會(huì)得到如下結(jié)果川尖,可以看到首次檢測(cè)時(shí)檢查了所有組件登下,包括ReferComponent,檢測(cè)從上到下逐個(gè)檢測(cè)。點(diǎn)擊改名按鈕后再次檢測(cè)時(shí)則只檢測(cè)有變化的那一側(cè)組件(RankParentComponent被芳,RankChildrenComponent)缰贝。其中我們可以觀察到,雖然在AppComponent中輸入屬性也發(fā)生了變化并且也更新了視圖畔濒,但是ngOnChanges鉤子卻沒有檢測(cè)到變化剩晴,注意這是一個(gè)坑。
那么什么是單向數(shù)據(jù)流呢侵状?其實(shí)簡(jiǎn)單理解就是angular檢測(cè)到數(shù)據(jù)變化到更新完視圖的過(guò)程中數(shù)據(jù)是不應(yīng)該被改變的赞弥,如果我們?cè)谶@期間更改了數(shù)據(jù),Angular便會(huì)拋出一個(gè)錯(cuò)誤趣兄,舉個(gè)例子绽左,我們?cè)赗ankChildrenComponent的ngAfterViewChecked鉤子函數(shù)中更改childName的值,在控制臺(tái)會(huì)看到如下錯(cuò)誤艇潭。
import {AfterViewChecked, Component, Input, OnChanges, OnInit} from '@angular/core';
@Component({
selector: 'app-rank-children',
templateUrl: './rank-children.component.html',
styleUrls: ['./rank-children.component.css']
})
export class RankChildrenComponent implements OnInit,OnChanges,AfterViewChecked {
@Input() childName;
constructor() { }
ngOnChanges(changes) {
console.dir(changes);
}
ngOnInit() {
}
ngAfterViewChecked(){
this.childName = "我要試著改變一下"
}
}
如果必須要更改這個(gè)屬性的值拼窥,能不能做呢?答案是可以的蹋凝。結(jié)合剛次提到的單向數(shù)據(jù)流闯团,如果我們把這次數(shù)據(jù)變更放到下一輪Angular變更檢測(cè)中,就能解決這個(gè)問(wèn)題了仙粱。怎么做呢房交?刻意異步一下就行了。是不是很神奇伐割?
ngAfterViewChecked(){
setTimeout(()=>{
this.childName = "我要試著改變一下"
},0)
}
至于angular為什么要采用單向數(shù)據(jù)流候味,其實(shí)也很好理解,最主要的就是防止數(shù)據(jù)模型和視圖不統(tǒng)一隔心,同時(shí)也可以提高渲染的性能白群。
4.如何優(yōu)化檢測(cè)性能
講了這么多,所以到底有什么用呢硬霍?其實(shí)在 Angular 中帜慢,每一個(gè)組件都都它自己的檢測(cè)器(detector),用于負(fù)責(zé)檢查其自身模板上綁定的變量唯卖。所以每一個(gè)組件都可以獨(dú)立地決定是否進(jìn)行臟檢查粱玲。默認(rèn)情況下,變化檢測(cè)系統(tǒng)將會(huì)走遍整棵樹(defalut策略)拜轨,但我們可以使用OnPush變化檢測(cè)策略抽减,利用 ChangeDetectorRef實(shí)例提供的方法,來(lái)實(shí)現(xiàn)局部的變化檢測(cè)橄碾,最終提高系統(tǒng)的整體性能卵沉。
來(lái)颠锉,舉個(gè)例子。在ReferComponent中史汗,我們?cè)O(shè)個(gè)定時(shí)器2秒以后更新一個(gè)非輸入屬性的值琼掠,在默認(rèn)策略時(shí),可以發(fā)現(xiàn)2秒以后視圖中的值發(fā)生了改變停撞,但是當(dāng)我們把策略改為Onpush時(shí)眉枕,除了在AppComponent點(diǎn)擊按鈕改變輸入屬性justRefer外,其他屬性改變不會(huì)引起視圖更新怜森,ReferComponent組件的檢測(cè)也被略過(guò)。我們可以這么總結(jié):OnPush 策略下谤牡,若輸入屬性沒有發(fā)生變化副硅,組件的變化檢測(cè)將會(huì)被跳過(guò)。
refer.component.ts
import {ChangeDetectionStrategy, Component, Input, OnChanges, OnInit} from '@angular/core';
@Component({
selector: 'app-refer',
templateUrl: './refer.component.html',
styleUrls: ['./refer.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ReferComponent implements OnInit, OnChanges {
@Input() justRefer;
notInput: any = {
tip: ''
};
originData: any = {
tip: '這不是輸入屬性'
};
constructor() {
}
ngOnInit() {
setTimeout(() => {
this.notInput = this.originData;
}, 2000);
}
ngOnChanges(changes) {
console.dir(changes);
}
}
可是我就是要更改非輸入屬性怎么辦呢翅萤?別急恐疲,Angular早就為你想好了。在Angular中套么,有這么一個(gè)class:ChangeDetectorRef 培己,它是組件的變化檢測(cè)器的引用,我們可以在組件中的通過(guò)依賴注入的方式來(lái)獲取該對(duì)象,來(lái)手動(dòng)控制組件的變化檢測(cè)行為胚泌。它提供了以下方法供我們調(diào)用
class ChangeDetectorRef {
markForCheck(): void
detach(): void
detectChanges(): void
checkNoChanges(): void
reattach(): void
}
- markForCheck() - 在組件的 metadata 中如果設(shè)置了 changeDetection: ChangeDetectionStrategy.OnPush 條件省咨,那么變化檢測(cè)不會(huì)再次執(zhí)行,除非手動(dòng)調(diào)用該方法玷室。
- detach() - 從變化檢測(cè)樹中分離變化檢測(cè)器零蓉,該組件的變化檢測(cè)器將不再執(zhí)行變化檢測(cè),除非手動(dòng)調(diào)用 reattach() 方法穷缤。
- reattach() - 重新添加已分離的變化檢測(cè)器敌蜂,使得該組件及其子組件都能執(zhí)行變化檢測(cè)
- detectChanges() - 從該組件到各個(gè)子組件執(zhí)行一次變化檢測(cè)
現(xiàn)在我們來(lái)試試解決剛才那個(gè)問(wèn)題,我們對(duì)ReferComponent做如下改造津肛。
constructor(private changeRef:ChangeDetectorRef) {
}
ngOnInit() {
setTimeout(() => {
this.notInput = this.originData;
this.changeRef.markForCheck();
}, 2000);
}
ok章喉,現(xiàn)在看到在Onpush策略下手動(dòng)修改非輸入屬性的值,視圖也可以及時(shí)更新了身坐。其他的幾個(gè)方法也都大同小異秸脱,感興趣的可以逐個(gè)試試。