Google Analytics in Angular App — Example
Do you need to measure traffic on your Angular routes? Then you are here right. In this example I will demonstrate how to create simple and elegant Angular service to measure traffic on your Angular App with Google Analytics.
Prerequisites
You should have already set up you Google Analytics account and have your UA-XXXXXXXX-X.
Example
First of all we will include Google Analytics in index.html.
<!doctype html> | |
<head> | |
<script> | |
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)})(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); | |
ga('create', 'UA-XXXXXXXX-X', 'auto'); | |
</script> | |
</head> | |
<body> | |
<app-root></app-root> | |
</body> | |
</html> | |
Then we will create our Google Analytics service. Here we will subscribe for routing events, but only when we are in production.
import { Injectable } from '@angular/core'; | |
import {Router, NavigationEnd} from '@angular/router'; | |
import { environment } from '../../environments/environment'; | |
declare var ga:Function; // <-- Here we declare GA variable | |
@Injectable() | |
export class GoogleAnalyticsService { | |
constructor(router: Router) { | |
if (!environment.production) return; // <-- If you want to enable GA only in production | |
router.events.subscribe(event => { | |
if (event instanceof NavigationEnd) { | |
ga('set', 'page', event.url); | |
ga('send', 'pageview'); | |
} | |
}) | |
} | |
} |
The last step is app.module.ts, where we will inject our GoogleAnalyticsService.
import { BrowserModule } from '@angular/platform-browser'; | |
import { NgModule } from '@angular/core'; | |
import { environment } from '../environments/environment'; | |
import { AppComponent } from './app.component'; | |
import {GoogleAnalyticsService} from "./services/google-analytics.service"; | |
@NgModule({ | |
declarations: [ | |
AppComponent | |
] | |
providers: [ | |
GoogleAnalyticsService | |
], | |
bootstrap: [AppComponent] | |
}) | |
export class AppModule { | |
constructor(protected _googleAnalyticsService: GoogleAnalyticsService) { } <-- We inject the service here to keep it alive whole time | |
} |
And we are set up. Now we can test it, don’t forgot to comment out production mode line in GoogleAnalyticsService, when in dev environment. Here is screen from one of my apps.