Angular2學(xué)習(xí)教程之ng中變更檢測問題詳解
開發(fā)中遇到的問題
在開發(fā)中遇到一個(gè)這樣的問題,代碼不便透露,這里用簡單的例子還原一下問題所在:
有三個(gè)組件,第一個(gè)是用來展示Todo列表的組件TodoComponent,Todo是個(gè)類,包含id和name屬性。
@Component({ selector: 'todo-list', template: ` <p *ngFor='let item of todos'>{{ item.name }}</p> `, }) export class TodoComponent{ @Input() todos: Todo[]; public getTodos():Todo[]{ return this.todos; } }
第二個(gè)組件同樣是一個(gè)Todo列表展示組件TodoDataComponent ,不同的是該組件需要一個(gè)TodoComponent類型的輸入,并從TodoComponent組件中獲得需要展示的Todo數(shù)據(jù)。
@Component({ selector: 'app-todo-data', template: `<p *ngFor='let item of todos'>{{ item.name }}</p> <button (click)='getData()'>get data</button>`, styleUrls: ['./todo-data.component.css'], inputs: ['todoComponent'], }) export class TodoDataComponent implements OnInit { todoComponent: TodoComponent; todos: Todo[] constructor() { } ngOnInit() { } getData(){ this.todos=this.todoComponent.getTodos(); } }
最后一個(gè)是應(yīng)用的根組件,根組件根據(jù)loading值來確定是否加載TodoComponent組件,并展示TodoDataComponent 組件。
//app.component.htm <div> <div *ngIf='loading'> <todo-list [todos]='todos'></todo-list> <button (click)='changeall()'>next</button> </div> </div> <div> <app-todo-data [todoComponent]='todoComponent'></app-todo-data> </div> //app.component.ts @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], }) export class AppComponent implements OnInit { todos: Todo[]; @ViewChild(TodoComponent) todoComponent: TodoComponent; loading: boolean = true; constructor(private todoService:TodoService){ super(true); } ngOnInit(){ this.todoService.todos.subscribe(data => {this.todos=data}); this.todoService.load(0, 3); } changeall(){ this.todoService.load(3, 3); } }
這樣問題就來了,TodoComponent 組件是否在頁面上展示是不確定的,在上面的例子中根組件最開始沒有渲染TodoComponent組件,最后根據(jù)loading的值將TodoComponent渲染出來。而TodoDataComponent 組件的顯示又需要一個(gè)TodoComponent 進(jìn)行初始化(跟組件通過@ViewChild(TodoComponent)
獲得),這樣造成在開發(fā)模式下出現(xiàn)以下錯(cuò)誤:
template:9:16 caused by: Expression has changed after it was checked. Previous value: 'undefined'. Current value: '[object Object]'
.
該錯(cuò)誤僅在開發(fā)模式下會(huì)報(bào)告出來的,解決掉總是更好的選擇,防止在生產(chǎn)環(huán)境下出現(xiàn)問題。
問題的原因及解決辦法
這個(gè)問題是ng2中的變更檢測策略造成的,ng2并沒有智能到一有數(shù)據(jù)變更就能自動(dòng)檢測到的,執(zhí)行變更檢測的一些情況有:組件中的輸入發(fā)生變化、組件中有事件響應(yīng)、setTimeOut函數(shù)等。
這樣在上面的小例子中, @ViewChild(TodoComponent)todoComponent: TodoComponent;
從undefined到[object Object],而并沒有觸發(fā)ng的變更檢測。
解決辦法也很簡單,ng支持手動(dòng)觸發(fā)變更檢測,只要在適當(dāng)?shù)奈恢?,調(diào)用變更檢測即可。
在上面的例子中,解決辦法為:
從@angular/core引入AfterViewInit, ChangeDetectorRef。注入ChangeDetectorRef對象,并在聲明周期鉤子ngAfterViewInit中調(diào)用變更
constructor(private todoService:TodoService, private cdr: ChangeDetectorRef){} ngAfterViewInit(){ this.cdr.detectChanges(); }
ChangeDetectorRef
用來處理ng變更的類,可以使用它來進(jìn)行完全的手動(dòng)變更檢測,主要有一下方法:
1.markForCheck()
標(biāo)記為需要進(jìn)行變更檢測,官方給的一下例子,setInterval不會(huì)觸發(fā)變更檢測,因此模板上的numberOfTicks 并不會(huì)發(fā)生變化。
setInterval(() => { this.numberOfTicks ++ // the following is required, otherwise the view will not be updated this.ref.markForCheck(); }, 1000);
2.detach()從變更檢測樹上分離,即該組件不會(huì)進(jìn)行自動(dòng)的變更檢測,變更需要手動(dòng)進(jìn)行,使用detectChanges函數(shù)。
3.detectChanges()手動(dòng)檢測變更,當(dāng)變更檢測代價(jià)較大時(shí),可以設(shè)置為定時(shí)進(jìn)行表更檢測
ref.detach(); setInterval(() => { this.ref.detectChanges(); }, 5000);
4.checkNoChanges()
進(jìn)行變更檢測,有變更時(shí)拋出異常
5.reattach()
與detach()
方法的作用相反
其他一些變更檢測知識(shí)
angular2中的每一個(gè)組件都關(guān)聯(lián)到一個(gè)變更檢測器,ChangeDetectorRef可以用來控制變更檢測器進(jìn)行檢測。
瀏覽器的以下行為可以出發(fā)檢測器進(jìn)行檢測:
1.所有瀏覽器事件
2.setTimeout()
和setInterval()
3.Ajax請求
OnPush變更檢測模式
組件默認(rèn)使用的是Default變更檢測模式,只要組件的輸入發(fā)生變化時(shí),就會(huì)觸發(fā)檢測器的執(zhí)行。除Default模式外,還有一種OnPush變更檢測模式,使用該模式首先需要在組件聲明修飾符中添加
@Component({ selector: 'todo-list', changeDetection: ChangeDetectionStrategy.OnPush, })
聲明為OnPush變更檢測模式意味著當(dāng)組件輸入發(fā)生變化時(shí),不一定會(huì)觸發(fā)變更檢測器,只有當(dāng)該輸入的引用發(fā)生變化時(shí),檢測器才會(huì)觸發(fā)。例如在一個(gè)數(shù)組中某個(gè)下標(biāo)的值發(fā)生變化時(shí),檢測器不會(huì)觸發(fā),視圖不會(huì)更新,只有該數(shù)組引用發(fā)生變化時(shí),視圖才會(huì)更新。當(dāng)然瀏覽器事件、observable發(fā)出的事件等還是會(huì)觸發(fā)檢測器的。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家腳本之家的支持。
相關(guān)文章
AngularJS自定義指令實(shí)現(xiàn)面包屑功能完整實(shí)例
這篇文章主要介紹了AngularJS自定義指令實(shí)現(xiàn)面包屑功能,結(jié)合完整實(shí)例形式分析了AngularJS自定義指令的定義、調(diào)用及面包屑功能的具體實(shí)現(xiàn)技巧,需要的朋友可以參考下2017-05-05AngularJS使用ng-app自動(dòng)加載bootstrap框架問題分析
這篇文章主要介紹了AngularJS使用ng-app自動(dòng)加載bootstrap框架問題,分析了前面文章中所述的ng-app自動(dòng)加載bootstrap出現(xiàn)的錯(cuò)誤原因與相應(yīng)的解決方法,需要的朋友可以參考下2017-01-01angularjs使用directive實(shí)現(xiàn)分頁組件的示例
本篇文章主要介紹了angularjs使用directive實(shí)現(xiàn)分頁組件的示例,具有一定的參考價(jià)值,有興趣的可以了解一下。2017-02-02Angular模版驅(qū)動(dòng)表單的使用總結(jié)
這篇文章主要介紹了Angular模版驅(qū)動(dòng)表單的使用總結(jié),本文實(shí)現(xiàn)了Angular支持表單的雙向數(shù)據(jù)綁定,校驗(yàn),狀態(tài)管理,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2018-05-05