In angular2, the advantage of using zone.run vs changeDetecotor.markForCheck ()

I am wondering what the advantage or disadvantage of using one over the other:

constructor(private app:ApplicationRef, private ref:ChangeDetectorRef) { this.ref.markForCheck(); // OR this.ref.detectChanges() // will do same thing? ... 

against

 zone.run (() => doSomething()) ... 

against

  app.tick(); 

all of them will essentially mark the component for checking and updating / redrawing the user interface.

I know that app.tick() will do this for the entire application, but in my tests it did not actually force the user interface to be updated.

zone.run and markforCheck force the user interface to be updated the next time the zone cycle is checked, so why use one over the other?

+3
angular
Jun 05 '16 at 15:31
source share
1 answer

If you run code that only affects the current component, for example

 someServiceThatRunsOutsideZone.getData() .subscribe(data => { this.data = data; this.ref.markForCheck(); }); 

this.ref.markForCheck() excellent.

If you do, for example, this.router.navigateXxx(...) outside the corner zone, then it is difficult to understand whether this.ref.markForCheck() cover all elements that can change their state with this rather complicated operation.

In addition, if this.router.navigateXxx(...) calls some asynchronous calls, your markForCheck will be launched before these asynchronous calls are completed and will not cause change detection at the end, as it is probably necessary.

FROM

 this.zone.run(() => this.router.navigateXxx(...)) 

it doesn’t matter because this.router.navigateXxx() and all the code called by this call (sync and async) will work inside the Angulars zone and use its corrected API.

I don't know about the exact difference between app.tick and markForCheck , but app.tick also has the drawback described above for markForCheck

+1
Jun 05 '16 at 15:43
source share



All Articles