Skip to content

Instantly share code, notes, and snippets.

@ggreenleaf
Last active January 13, 2022 17:47
Show Gist options
  • Select an option

  • Save ggreenleaf/a7cab0dcde93c980ecb871c4e56ad07f to your computer and use it in GitHub Desktop.

Select an option

Save ggreenleaf/a7cab0dcde93c980ecb871c4e56ad07f to your computer and use it in GitHub Desktop.
Sample of linking google analytics with angular
// Google Analytics Service
init() {
if (!this.scriptsLoaded) {
this.insertMainScript();
}
}
trackPageViews() {
return this.router.events.pipe(
filter(() => this.scriptsLoaded),
filter((event: RouterEvent) => event instanceof NavigationEnd),
tap((event: NavigationEnd) => this.trackSinglePageView(event))
);
}
setCurrentUser(userId: string) {
// we set this in the get user function of Auth service
// to avoid this being set several times we have a flag to check if it was set initially
if (this.googleAnalyticsId && this.scriptsLoaded && !this.userIdSet) {
gtag('set', { user_id: userId });
this.userIdSet = true;
}
}
private trackSinglePageView(event: NavigationEnd) {
if (this.googleAnalyticsId && this.scriptsLoaded) {
gtag('config', this.googleAnalyticsId, { page_path: event.urlAfterRedirects, send_page_view: true });
}
}
private insertMainScript() {
if (this.googleAnalyticsId) {
const script: HTMLScriptElement = this.renderer2.createElement('script');
script.type = 'text/javascript';
script.onload = this.insertSecondHalfOfScript.bind(this);
script.src = `https://googletagmanager.com/gtag/js?id=${this.googleAnalyticsId}`;
script.text = '';
this.renderer2.appendChild(this.document.body, script);
}
}
private insertSecondHalfOfScript() {
const script: HTMLScriptElement = this.renderer2.createElement('script');
script.type = 'text/javascript';
script.src = '/assets/config/google-analytics.js';
script.text = '';
this.renderer2.appendChild(this.document.body, script);
script.onload = () => {
this.scriptsLoaded = true;
};
}
// App component
ngOnInit() {
this.googleAnalytics.init();
this.googleAnalytics.trackPageViews().pipe(takeUntil(this.destroySubject$)).subscribe();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment