Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf(plugin-angular): do not run change detections when notifying the event #1422

Open
wants to merge 1 commit into
base: next
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion packages/plugin-angular/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
import { ErrorHandler, Injectable } from '@angular/core'
import Bugsnag, { Client, Plugin } from '@bugsnag/js'

// This actually should be `ZoneType`, but we can't type it since the `zone.js`
// package may not be installed.
declare const Zone: any;

// There're 2 types of Angular applications:
// 1) zone-full (by default)
// 2) zone-less
// The developer can avoid importing the `zone.js` package and tells Angular that
// they are responsible for running the change detection by themselves. This is done by
// "nooping" the zone through `CompilerOptions` when bootstrapping the root module (`{ ngZone: 'noop' }`).
const isNgZoneEnabled = typeof Zone !== 'undefined' && !!Zone.root && typeof Zone.root.run === 'function'

@Injectable()
export class BugsnagErrorHandler extends ErrorHandler {
public bugsnagClient: Client;
Expand Down Expand Up @@ -35,7 +47,19 @@ export class BugsnagErrorHandler extends ErrorHandler {
})
}

this.bugsnagClient._notify(event)
if (isNgZoneEnabled) {
// The `Zone.root.run` will spawn asynchronous tasks within the root zone, a parent for the Angular forked zone.
// That means that `zone.js` won't notify the forked zone about invoking tasks; thus, change detection will not
// be triggered multiple times through `ApplicationRef.tick()`.
// Caretaker note: we could've used `NgZone.runOutsideAngular`, but this will require injecting the `NgZone`
// facade. That will create a breaking change for projects already using the `BugsnagErrorHandler`.
Zone.root.run(() => {
this.bugsnagClient._notify(event)
})
} else {
this.bugsnagClient._notify(event)
}

ErrorHandler.prototype.handleError.call(this, error)
}
}
Expand Down