To get the most out of Application Insights when building a Single Page Application, some specific tweaks are required. Let's walk through the steps to get Application Insights configured in your Angular application.
I expect that you already configured an Application Insights resource in the Azure Portal and have an existing Angular application.
Step 1 - Add dependencies and configuration settings
We’ll start by adding an extra dependency ‘@microsoft/applicationinsights-web’ to our package.json:
We also update our environment.ts file to store our Application Insights instrumentation key there:
Step 2 – Create an Angular Service to wrap the Application Insights SDK
We create an Angular service that we will use as a wrapper around the Application Insights SDK. Here we inject the AppInsights class.
Notice that we set both the ‘enableCorsCorrelation’
and ‘enableAutoRouteTracking’
to true
. This will correctly inject a correlation-id in our request headers and will track all route changes as navigation events.
We can further expand this service with extra methods to explicitly call specific functionality of the Application Insights SDK:
Step 3 – Consume the service in our Angular application
To consume the service as soon as the application starts, we’ll inject it in our AppComponent:
We can go one step further by creating our own ErrorHandler instance so that all client side exceptions are nicely logged in Application Insights:
Don’t forget to configure the AppModule to use this handler: