Stepan Suvorov
Stepan Suvorov

Reputation: 26226

ngZone or zone.js: the place of monkey-patching?

I'm learning how ngZone works in Angular. I understood that it's doing monkey-patching of standard async operations(such as setTimeout).

But who is doing monkey-patching? zone.js library or Angular itself within ngZone? It would be great if you could show specific place in source code where it happens.

Upvotes: 2

Views: 2035

Answers (3)

Manish Bansal
Manish Bansal

Reputation: 2681

Monkey patching is done by Zone.js. In ng_zone.ts, zone.ts is loaded which creates the root zone as well as monkey patches the API.

NGZone simply forks a child zone named 'angular' and provides callbacks in zone specifications. In those callbacks, it emits events which are further subscribed in application_ref.ts and change detection is kicked off.

Monkey Patching: This is done by calling Zone.__load_patch() function with 2 arguments. First argument is the identifier of the monkey-patched APIs and second is the patch function which when executed, replaces the actual browser API with the re-defined version.

Now, this is just the tip of the iceberg. Actual magic is done by calling patchMethod() of utils.ts. For set/clearTimeOut case, this is done here.

In patchMethod(), original api is saved in local variable i.e. delegate and the same is returned which is saved in setNative variable inside timers.ts.

For complete workflow, you can refer below article.

https://medium.com/reverse-engineering-angular/angular-deep-dive-zone-js-how-does-it-monkey-patches-various-apis-9cc1c7fcc321

Upvotes: 1

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657841

Angular runs the zone within zone.js, and zone.js provides a scope with patched API.

You can yourself use zone.run(...) without anything from Angular and get all the effects of the patched API.

See also https://github.com/angular/zone.js/

The code that patches the timer https://github.com/angular/zone.js/blob/master/lib/common/timers.ts#L22

Upvotes: 2

Reactgular
Reactgular

Reputation: 54811

The zone library has to work in both the browser and server-side projects. So it's a little more complicated than just patching global functions.

Zone not only patches global APIs, but also patches event objects as they are broadcasted. The patching is done via Zone.__load_patch and you can see what is being patched in these modules.

https://github.com/angular/zone.js/blob/master/lib/browser/browser.ts

https://github.com/angular/zone.js/blob/master/lib/node/node.ts

https://github.com/angular/zone.js/blob/master/lib/rxjs/rxjs.ts

It's clearly not a simply process. I'm sure there are still some edge cases that zone hasn't patched.

Upvotes: 1

Related Questions