Created
August 4, 2020 02:01
-
-
Save a11smiles/f54e7e2ab9648e62d220f4e004f5bf6c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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