Search⌘ K
AI Features

Adding in Analytics

Explore how to integrate an analytics service that tracks route changes in Angular applications. Understand using RxJS to listen for navigation events and log page views effectively, enabling better monitoring of user navigation patterns.

Routing analytics

Let’s hook up some analytics trackers to Angular’s router. Instead of listening in on individual routes, this service needs to know about every route change. Generate a new service and attach it to the routing module with ng g service analytics.

⚠️ While working locally, make sure you’re on the latest version of the Angular CLI. Older versions will fail, with "Error: Specified module does not exist."

Open the fresh analytics.service.ts and modify it to add in some structure for recording routing changes:

TypeScript 3.3.4
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class AnalyticsService {
constructor() { }
recordPageChange(event) {
// Call your analytics library
console.log('Route triggered', event.urlAfterRedirects);
}
}

Components analytics

This service just logs any route change to the console. You can import any analytics tool to connect the external tool with Angular. The real excitement goes on in app.component.ts:

TypeScript 3.3.4
export class AppComponent implements OnInit {
title = 'app';
constructor(private router: Router, private analytics: AnalyticsService) { }
ngOnInit() {
this.router.events
.pipe(
filter(event => event instanceof NavigationEnd)
)
.subscribe(event => {
this.analytics.recordPageChange(event);
});
}
}
  • Line 4: AppComponent now requires injecting both the Router and the newly created AnalyticsService. Don’t forget to import these.

  • Line 7: As covered before, router.events is an observable that emits on any event the router might care to send off.

  • Line 9: The analytics code only cares about recording page loads, so we filter out any emitted event that isn’t an instance of NavigationEnd.

  • Line 12: Finally, inform the analytics code that there’s been a new page change.

There are other events to listen in for, but this serves as a simple example for capturing events on the router.

import { AppPage } from './app.po';

describe('rx-photos App', () => {
  let page: AppPage;

  beforeEach(() => {
    page = new AppPage();
  });

  it('should display welcome message', () => {
    page.navigateTo();
    expect(page.getParagraphText()).toEqual('Welcome to app!');
  });
});
Adding Analytics

Analytics log in console

📝 Please note that the Console in the above illustration is a feature of the Chrome browser, that can be used by opening the application in the new tab and using the Inspect feature of the Chrome browser.