Adding Application Insights to Angular

I love to watch tutorials, but I really learn when I write out the instructions.  I decided to break down the instructions from the following tutorial: Angular monitoring using Azure Application Insights by clouddeveloper.io . I like to visually see clear steps when I look back on my notes.  So this will help me as my work is implementing Azure Application Insights for their products.  However, I figured I’d throw it up on my blog incase anyone found it useful. 

Be sure to watch the video in tandem with these notes as this isn’t a word by word transcription.  The teacher adds a lot of commentary about the code and Insights more broadly that you will find very useful.  Also, remember that he is using his own pre-built angular app so the folders and file structure may be different for your application.  

 

1. Add Application Insights to your package.json file

npm install applicationinsights-js --save

2. Add Application Insights to dev dependencies

npm install @types/applicationinsights-js --save-dev

3. Launch/Serve your angular application.


4. Create a service, which is essentially a wrapper around the Application Insights that we can easily manage and use throughout the application.


5. Navigate to your app folder. Create a services folder and put in AppInsights. Also specify the module ==> This is important because it will create the module for us and update the app.module file (shows up in imports and in providers).


ng g service services/AppInsights --module=app.module

6. Open your app-insights.service.ts file. Add a few imports: the environment configuration to actually store application insights key inside of the environment configuration and just use it inside of the service.

import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import { AppInsights } from 'applicationinsights-js';

7.  Open environment file. Add the specific key for Application Insights. Find the Instrumentation Key value in your Azure portal.

export const environment = {
   production: false,
   appInsights: {
   instrumentationKey: '0e0e0000-0000-0cb0-000c-0d00bc000fe0'
   }
};

8. Create a configuration object for our service. This is something that will be passed into the application insights library so that it knows about the actual Instrumentation Key.

import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import { AppInsights } from 'applicationinsights-js';

@Injectable()
export class AppInsightsService {
  private config: Microsoft.ApplicationInsights.IConfig = {
    instrumentationKey: environment.appInsights.instrumentationKey
  }
  constructor() {}

}

9. Within the constructor, we want to check and see if the Application Insights is actually initialized. This will tell your service to go ahead and initialize the Application Insights and download all the required libraries from the CDN. It will pull down the Application Insights specific javascript file.

import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import { AppInsights } from 'applicationinsights-js';

@Injectable()
export class AppInsightsService {
  private config: Microsoft.ApplicationInsights.IConfig = {
    instrumentationKey: environment.appInsights.instrumentationKey
  }
  constructor() {
    if(!AppInsights.config) {
      AppInsights.downloadAndSetup(this.config);
    }
  }

10. Add two methods: logPageView – used to allow us to call page view to say when our application loads we want to track that somebody loaded a particular page. logEvent which will allow us to do things like log events around components loading, or if somebody clicks on something, we can invoke the log event to be able to track that particular event.

import { Injectable } from '@angular/core';
import { environment } from '../../environments/environment';
import { AppInsights } from 'applicationinsights-js';

@Injectable()
export class AppInsightsService {
  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);
  }

}

11. Go to app.component.ts and import the AppInsightsService itself.

import { AppInsightsService } from './services/app-insights.service';

12. Invoke a constructor. Invoke a method to logPageView.

export class AppComponent implements OnInit {
  title = 'clouddeveloper.io';

  constructor(appInsightsService: AppInsightsService) {
    appInsightsService.logPageView('MainPage'); //MainPage is just a name you want to call the page.
  }

app.component.ts file should now look like this:

import { Component, OnInit } from '@angular/core';
import { environment } from '../environments/environment';
import { AppInsightsService } from './services/app-insights.service';

declare var $: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
  })

export class AppComponent implements OnInit {
  title = 'clouddeveloper.io';

  constructor(appInsightsService: AppInsightsService) {
    appInsightsService.logPageView('MainPage'); //MainPage is just a name you want to call the page.
  }
  
  ngOnInit(): void {
    // Only trigger Application Insight tracking if we are running in production otherwise we'll get too many hits that are useless.
    if (environment.production) {
      this.insightService.logPageView('Home');
    }
    $(window).scroll(function(){
        let wScroll = $(this).scrollTop();
        $('.logo').css({
          'transform': 'translate(0px, ' + wScroll * 1.53 + '%)'
        });
    });
  }