Analytics
angular

Updated: Angular Spa App with Google Analytics in a few easy steps

Reading Time: 3 minutes

About a year ago, I wrote some code to quickly add google analytics to your angular spa app. As with any code, it’s changed a bit over time. I recently had a github request asking how to turn the analytics on or off based on the environment you are in (dev, prod, etc). I posted a quick update but then refactored it to be more flexible and I thought I’d explain the latest updates here.

You can find the latest code here on GitHub

Overall, the actual code hasn’t changed much . The main differences are the following:

  1. I removed the actual ga(...) calls from assests/js/google-analytics.js and moved them into the google-analytics.service.ts
    • You will still need the the assets/js/google-analytics.js but that’s just to load and prep the google scripts
  2. I updated the environments.ts & environments.prod.ts file with a few more configurations for setting up preferred behaviors
  3. I updated the google-analytics.service.ts to load values from the environment.ts file

Step 1 – Remove the ga(…) calls from assests/js/google-analytics.js

// removed the => function and made it function() for backward compatibility
loadScript("https://www.google-analytics.com/analytics.js", function() {

  window.ga=window.ga||function(){ (ga.q=ga.q||[]).push(arguments); };
  ga.l=+new Date();

  // removed the ga calls form here, they are now called in the service.
  // this is more flexible and configurable.  UAID's can be be stored in the environment.*.ts files

});

Step 2 – Update your environment variables

Set your variables to desired values

NOTES: You need to do this for all your environment.xx.ts files.  Assuming you only have the defaults, that the main environment.ts file and the production file environment.prod.ts (which gets injected into / overrides the environment.ts file) with the –prod flag on ng builds / ng serves

Technically, this allows you to have a separate UaId for Development, Prod, Staging, Demo’s, etc.

export const environment = {
  production: false,
  name: 'local-dev',
  google: {
    analytics: {
      active: true,
      uaId: 'UA-xxxxxxx-1',
      logging : {
        debug: true,
        exceptions: true,
        verbose: true,
      }
    }
  }
};

Step 3 – Updated google-analytics.service.ts

There’s a lot of updates to this file, I suggest you just look thought it but here’s the highlights:

Loading the Environment Variables into this service. 

Reminder: you only reference the main environment (environment.ts) file.  That’s the one baked into the code during the build.  If you use the –prod flag or configuration=some-other-config, the corresponding environment.xx.ts file overwrites, the main environment.ts file, so it’s the only one you need to worry about.  For more information on how this works read this article

import { environment } from '../../../../environments/environment';

Load the values into some local variables (not required, but easier to work with than calling out the full object path)

// tslint:disable-next-line:no-non-null-assertion
  private readonly logging = environment!.google!.analytics!.logging;
  // tslint:disable-next-line:no-non-null-assertion
  private readonly isActive: boolean = environment!.google!.analytics!.active;
  // tslint:disable-next-line:no-non-null-assertion
  private readonly UAId: string = environment!.google!.analytics!.uaId;

Some validation is added to makes sure we want to log a particular url.  For example this checks won’t allow us to log token data (assuming we’re using some sort of identity provider (and of course our token redirect is located at auth/token) .

if (e.urlAfterRedirects && this.isOkToLog(e.urlAfterRedirects)) {
  ...
}
private isOkToLog(url: string): boolean {

    // todo: add more blacklisted urls here (better yet, load them from the environments file)
    if (url.toString().indexOf('auth/token') !== -1) {
      if (this.logging && this.logging.verbose) {
        console.log(`don't track ${url}`);
      }
      return false;
    }

    if (this.logging && this.logging.verbose) {
      console.log(`track ${url}`);
    }

    return true;
  }

The actual ga(...) calls, some of which were previously in assests/js/google-analytics.js

(<any>window).ga('create', `${this.UAId}`, 'auto');
(<any>window).ga('set', 'page', e.urlAfterRedirects);
(<any>window).ga('send', 'pageview');

The rest is just configured logging actions based on settings in the environment

if (this.logging && this.logging.debug) {
       console.log(`logging: ${e.urlAfterRedirects} to google analytics`);
}
if (this.logging && this.logging.exceptions) {
               console.error(ex);
               console.error(`tracking failed - make sure you installed the scripts`);
            }

That’s it! Now you have a updated google analytics tracking service.

Happy Tracking!

Eric