Skip to content

Instantly share code, notes, and snippets.

@molcik
Last active November 18, 2017 11:40
Show Gist options
  • Select an option

  • Save molcik/72bc66719e4a38dd28f88ba7ffac74b9 to your computer and use it in GitHub Desktop.

Select an option

Save molcik/72bc66719e4a38dd28f88ba7ffac74b9 to your computer and use it in GitHub Desktop.
Google Analytics Angular 2 Service
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');
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment