Injecting the Service into Our Pages

On the previous page, we injected Application Insights into the app.component.ts to quickly capture page views. Over the next few sections, we going to provide some functionality for gathering telemetry and events from our pages.

Application Insights Event Logging Methods

You will notice that the ApplicationInsightsService has some predefined methods for capturing various telemetry from our application. In order to utilize those methods, we will need to inject the service into each of our pages. Remember, on the first page, we injected the service into our app.component.ts, but this injection doesn’t give our pages access to the service or its methods. An alternative approach is to inject the service on each page, but that can be cumbersome.  Being that we want to track view and telemetry across all of our pages, a better approach would be to create a base component that all of our pages inherit. It is in this base component that we will inject our service.

So let’s create our base component (e.g. ng g c base-component). This will create the necessary component file and its unit tests specification file. In the component file, we’ll pretty much scrub all the UI references and simply inject our Application Insights service:

import { Component, OnInit } from '@angular/core';
import { ApplicationInsightsService } from '../application-insights.service';

@Component({
  template: '',
})
export class BasePageComponent implements OnInit {

  constructor(protected $aiService: ApplicationInsightsService) { }

  ngOnInit() {  }

}

Notice, we’ve removed the templateUrl and the stylesUrls properties from the @Component attribute, and we’ve replaced them with an empty template property (which is required). (You can also delete the base-page.component.html and base-page.component.scss files if you’d like as they are no longer needed.) A copy of the base-page.component.ts file can be found in the repository.

At this point, you can also remove the service injection from your app.component.ts as we’re going to let the base component register the page view and we don’t want to register the page view twice.

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  title = 'Application Insights Service';

  constructor() {  }

  ngOnInit() {  }
}

Now, instead of injecting the service into each component, we’ll simply modify our page components to inherit from our base component. The following is First Page‘s initial, modified source code.

import { Component, OnInit } from '@angular/core';
import { BasePageComponent } from '../base-page/base-page.component';

@Component({
  selector: 'app-first-page',
  templateUrl: './first-page.component.html',
  styleUrls: ['./first-page.component.scss']
})
export class FirstPageComponent extends BasePageComponent implements OnInit {

  ngOnInit() {
  }

}
  1. Notice that we’re importing our BasePageComponent (line 2)
  2. We extend (e.g. inherit) our FirstPageComponent from our BasePageComponent (line 9)
  3. Because BasePageComponent injects the ApplicationInsightsService in its constructor, FirstPageComponent doesn’t need any constructor.
    (NOTE: This is a VERY simple application/component. In larger applications, you may still need a constructor and then call super() and pass in an injected instance of the ApplicationInsightsService. But, that’s not necessary for our current application.)

In order to demonstrate Application Insights events, let’s add a button to our First Page HTML page.

<button (click)="click()">Click Me!</button>

We are going to bind the button to a click event in our TypeScript that will call our Application Insights methods.

Edit your first-page.component.ts and add the highlighted lines:

import { Component, OnInit } from '@angular/core';
import { BasePageComponent } from '../base-page/base-page.component';

@Component({
  selector: 'app-first-page',
  templateUrl: './first-page.component.html',
  styleUrls: ['./first-page.component.scss']
})
export class FirstPageComponent extends BasePageComponent implements OnInit {
  private _clickCnt = 0;

  ngOnInit() {
  }

  click() {
    this.$aiService.logEvent('click', { actor: 'Click Me! Button', page: 'First Page', count: ++this._clickCnt });
    console.log(`Button clicked ${this._clickCnt} times.`);
    console.log('Click for "First Page" sent!');
  }
}

When a user clicks the button, our click event will call the logEvent method of the injected ApplicationInsightsService (inherited from BasePageComponent) and the event will be available under the Events blade of your Application Insights instance.

The final version of the First Page‘s source can be found here.

With the click event wired up, go ahead and run your application again (remember, with the --prod flag). You’ll then begin to see events being logged in your Application Insights under the Events blade. Just be aware that Application Insights has a 5-minute delay. So once you click and navigate around the pages of your application, you’ll need to wait a few minutes to see the results show up in your Sessions and Events blades.

Conclusion

You’ve just added Application Insights to your application. There are more-robust approaches to doing this that are more suited for enterprise applications. But, this method is a “quick and dirty” attempt to get you up and running as soon as possible. This is also a great starter application for you to become more familiar with interacting with the Application Insights SDK.

Again, for the full source code to this project, check out my GitHub blog demos repository.