Add Application Insights to an Angular SPA


Laurie Atkinson, Senior Premier Developer Consultant, The steps and pieces you need to add logging and telemetry to an Angular SPA using Application Insights


Application Insights is an Azure service for monitoring web applications. It includes analytics tools to help you understand application usage and to diagnose issues with the goal of continuously improving performance and usability. In addition to its integration with a variety of backend web platforms, Application Insights also includes browser analytics.

The following steps are specifically targeted at the front-end developers building with Angular and TypeScript that want to start tracking their Single Page Applications.

Step 1 – Add Application Insights to your Azure subscription

  1. Navigate to portal.azure.com and log in.
  2. If an Application Insights resource has not been added yet (or you want to create a new one), select Add –> Monitoring + Management –> Application Insightclip_image002
  3. Fill in the required fields and click Create.clip_image004
  4. After the resource has been added, navigate to it via a search for Application Insights and note the instrumentation key located in the properties blade. This key is required to communicate between your web application and Application Insights.clip_image006

Step 2 – Configure Angular application and include dependencies

  1. Copy the instrumentation key into the Angular application. If your app was build using the Angular CLI, then you will have an environment.ts file which is a good place to store the instrumentation key. You may choose another file or service, but this key must be included in your project somewhere.
    export const environment = { 
        . . . 
        appInsights: { 
            instrumentationKey: 'b0137cf3-7ae6-4309-8925-06a3b1c20508' 
        } 
    }; 
    
  2. Add two dependencies to package.json and restore them using npm install.
    "dependencies": { 
    	"applicationinsights-js": "^1.0.8" 
    }, 
    "devDependencies": { 
    	"@types/applicationinsights-js": "^1.0.2", 
    } 
    

    applicationinsights-js – JavaScript library supplied by Microsoft to interface with the Application Insights SDK. Documentation on this library is located here.
    @types/applicationinsights-js – TypeScript type definition file for applicationinsights-js.

Step 3 – Consume the Application Insights SDK in TypeScript

  1. Create a TypeScript class as a wrapper around the Application Insights JavaScript API and import the AppInsights class using the module loading system. Include methods for each method in the SDK that you want to support.
    import { Injectable } from '@angular/core'; 
    import { environment } from '../../../environments/environment'; 
    import { AppInsights } from 'applicationinsights-js'; 
    
    @Injectable() 
    export class MyMonitoringService { 
    
    	private config: Microsoft.ApplicationInsights.IConfig = { 
    		instrumentationKey: environment.appInsights.instrumentationKey 
    	}; 
    
    	constructor() { 
    		if (!AppInsights.config) { 
    			AppInsights.downloadAndSetup(this.config); 
    		} 
    	} 
    
    	logPageView(name?: string, url?: string, properties?: any, 
    			measurements?: any, duration?: number) { 
    	AppInsights.trackPageView(name, url, properties, measurements, duration); 
    	} 
    
    	logEvent(name: string, properties?: any, measurements?: any) { 
    		AppInsights.trackEvent(name, properties, measurements); 
    	} 
    
        . . . 
    
    } 
    

    On creation, the service calls into the Application Insights SDK JavaScript API, which triggers the download of ai.js from a CDN. This is recommended to ensure that the latest JavaScript is running against the Application Insights API.

    If you are using the Angular CLI and webpack, then applicationinsights-js will be automatically included in the vendor bundle. If you are using SystemJS instead, you will need to make sure this module is included. It is located under node_modules in this path:

    clip_image008

  2. Create an instance of the class created in step 7 as soon as the application starts in the AppComponent.
    import { Component } from '@angular/core'; 
    import { MyMonitoringService } from './framework/logging/monitoring.service'; 
    
    @Component({ 
       . . . 
    }) 
    export class AppComponent { 
    	constructor(private myMonitoringService: MyMonitoringService) { 
    	} 
    } 
    
  3. The included JavaScript library will automatically send a number of metrics to Application Insights which are viewable in the Azure Portal under the Browser blade. Highlighted here are Page Views, Exceptions, and AJAX calls.clip_image010
  • Due to the nature of a Single Page Application (SPA), page transitions do not occur that would automatically trigger logging to Application Insights. To track the user’s activity as s/he navigates from page to page, a call must be made manually to trackPageView(). Rather than require the programmer to include this code in every component, you can include a base component and any component that should be tracked should inherit from this base class.
    import { Component, ReflectiveInjector } from '@angular/core'; 
    import { MyMonitoringService } from '../logging/monitoring.service'; 
    
    @Component({ 
    	template: '' 
    }) 
    export class BaseComponent { 
    
    	private myMonitoringService: MyMonitoringService; 
    
    	constructor() { 
    		// Manually retrieve the monitoring service from the injector 
    		// so that constructor has no dependencies that must be passed in from child 
    		const injector = ReflectiveInjector.resolveAndCreate([ 
    			MyMonitoringService 
    		]); 
    		this.myMonitoringService = injector.get(MyMonitoringService); 
    		this.logNavigation(); 
    	} 
    
    	private logNavigation() { 
    		this.myMonitoringService.logPageView(); 
    	} 
    } 
    

 

These steps should get your application up and running with Application Insights. To read about how to use the metrics being gathered, refer to this article. And, if you want to dig deeper into the API, you can read about using custom events and metrics.

Comments (1)

  1. Jay Stubbs says:

    Very clear and helpful. Thanks!

Skip to main content