Angular error tracking installation
- 1
Installing PostHog Angular SDK
RequiredYour goal in this step: Install the PostHog Angular SDK.Install
posthog-js
using your package manager:Initialize the PostHog client
Generate environment files for your project with
ng g environments
. Configure the following environment variables:posthogKey
: Your project API key from your project settings.posthogHost
: Your project's client API host. Usuallyhttps://us.i.posthog.com
for US-based projects andhttps://eu.i.posthog.com
for EU-based projects.
For Angular v17 and above, you can set up PostHog as a singleton service. To do this, start by creating and injecting a
PosthogService
instance.Create a service by running
ng g service services/posthog
. The service should look like this:posthog.service.tsThe service is initialized outside of the Angular zone to reduce change detection cycles. This is important to avoid performance issues with session recording.
Then, inject the service in your app's root component
app.component.ts
. This will make sure PostHog is initialized before any other component is rendered.app.component.ts Verify PostHog is initialized
CheckpointConfirm you can capture events with PostHogBefore proceeding, confirm that you can capture events with PostHog using
posthog.capture('test_event')
.- 2
Setting up exception autocapture
RequiredYour goal in this step: Enable automatic exception tracking for your Angular application.Exception autocapture can be enabled during initialization of the PostHog client to automatically capture any exception thrown by your Angular application.This requires overriding Angular's default
ErrorHandler
provider:src/app/posthog-error-handler.tsThen, in your
src/app/app.config.ts
, import theprovidePostHogErrorHandler
function and add it to the providers array:src/app/app.config.tsIf there are more errors you'd like to capture, you can manually call the
captureException
method:TypeScript - 4