Minimal Google Analytics Service | Task

Ole Ersoy
Apr - 14  -  2 min

Scenario

We need a minimal service for tracking router navigation events with Google Analytics.

Approach

First setup a property in Google Analytics and obtain the tracking code for it.

It will give you something like this when clicking on Tracking Info > Tracking Code in the admin area of Google Analytics. It should look like this:

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-140430388-3"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
gtag('config', 'UA-140430388-3');
</script>

Add the script to the head tag in index.html of your Angular project.

Service

First declare gtag in app.component.ts. This lets Typescript know that the gtag function has been defined elsewhere:

declare var gtag

The service looks like this:

/**
 * Google Analytics.
 */
import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { filter, map } from 'rxjs/operators';

declare var gtag

@Injectable({
  providedIn: 'root'
})
export class AnalyticsService {

  constructor(private r: Router) {
    const navEndEvents =
      r.events.pipe(
        filter(event => event instanceof NavigationEnd),
        map((event: NavigationEnd) => event.url))

    navEndEvents.subscribe(url => {
      if (gtag) {
        gtag('event', url, {
          'event_category': 'APP_NAVIGATION'
        })
      }
    })
  }
}

Whenever the user navigates the navEndEvents subscription will fire and track the navigation event for us.