Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save a11smiles/f54e7e2ab9648e62d220f4e004f5bf6c to your computer and use it in GitHub Desktop.
Save a11smiles/f54e7e2ab9648e62d220f4e004f5bf6c to your computer and use it in GitHub Desktop.
import { Injectable } from '@angular/core';
import { Router, RouterEvent, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
import { environment } from '../environments/environment';
declare var gtag: any;
@Injectable({
providedIn: 'root'
})
export class GoogleAnalyticsService {
constructor(private _router: Router) {
this._router.events.pipe(
filter(event => event instanceof NavigationEnd)
).subscribe((e: NavigationEnd) => {
gtag('js', new Date());
gtag('config', environment.googleAnalytics);
});
}
init() {
const script = document.createElement('script');
script.src = 'https://www.googletagmanager.com/gtag/js?id=UA-173474946-1';
script.async = true;
document.getElementsByTagName('head')[0].appendChild(script);
const gtagEl = document.createElement('script');
const gtagBody = document.createTextNode(`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
`);
gtagEl.appendChild(gtagBody);
document.body.appendChild(gtagEl);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment