Angular
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
Chapter 22: Zone.js<br />
Section 22.1: Getting reference to NgZone<br />
NgZone reference can be injected via the Dependency Injection (DI).<br />
my.component.ts<br />
import { Component, NgOnInit, NgZone } from '@angular/core';<br />
@Component({...})<br />
export class Mycomponent implements NgOnInit {<br />
constructor(private _ngZone: NgZone) { }<br />
ngOnInit() {<br />
this._ngZone.runOutside<strong>Angular</strong>(() => {<br />
// Do something outside <strong>Angular</strong> so it won't get noticed<br />
});<br />
}<br />
}<br />
Section 22.2: Using NgZone to do multiple HTTP requests<br />
before showing the data<br />
runOutside<strong>Angular</strong> can be used to run code outside <strong>Angular</strong> 2 so that it does not trigger change detection<br />
unnecessarily. This can be used to for example run multiple HTTP request to get all the data before rendering it. To<br />
execute code again inside <strong>Angular</strong> 2, run method of NgZone can be used.<br />
my.component.ts<br />
import { Component, OnInit, NgZone } from '@angular/core';<br />
import { Http } from '@angular/http';<br />
@Component({...})<br />
export class Mycomponent implements OnInit {<br />
private data: any[];<br />
constructor(private http: Http, private _ngZone: NgZone) { }<br />
ngOnInit() {<br />
this._ngZone.runOutside<strong>Angular</strong>(() => {<br />
this.http.get('resource1').subscribe((data1:any) => {<br />
// First response came back, so its data can be used in consecutive request<br />
this.http.get(`resource2?id=${data1['id']}`).subscribe((data2:any) => {<br />
this.http.get(`resource3?id1=${data1['id']}&id2=${data2}`).subscribe((data3:any) => {<br />
this._ngZone.run(() => {<br />
this.data = [data1, data2, data3];<br />
});<br />
});<br />
});<br />
});<br />
});<br />
}<br />
}<br />
GoalKicker.com – <strong>Angular</strong> 2 Notes for Professionals 97