Skip to content
This repository has been archived by the owner on Oct 14, 2024. It is now read-only.

ERROR ReferenceError: gtag is not defined when running npm run build:prerender #681

Open
kuncevic opened this issue Jun 6, 2019 · 2 comments

Comments

@kuncevic
Copy link

kuncevic commented Jun 6, 2019

Hi there, thank you guys for a great universal starter project that was really useful to me.

I just added the gtag to be able to track the google analytics router change event in my application that based on the universal starter.

Then when I run npm run build:prerender that giving me an error ERROR ReferenceError: gtag is not defined

I modified the starter with this code :

export class AppComponent implements OnInit {
  constructor(public router: Router) {}

  ngOnInit() {
    const navEndEvent$ = this.router.events.pipe(filter(e => e instanceof NavigationEnd));
    navEndEvent$.subscribe((e: NavigationEnd) => {
      gtag('config', 'UA-xxxxxxxxx-x', { page_path: e.urlAfterRedirects });
    });
  }
}

So you can reproduce it by cloning https://github.com/kuncevic/universal-starter

@kuncevic
Copy link
Author

kuncevic commented Jun 6, 2019

Had to wrap up the gtag() call to some additional code to fix the issue:

import { isPlatformBrowser } from '@angular/common';
import { Component, Inject, OnInit, PLATFORM_ID } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
import { filter } from 'rxjs/operators';
declare var gtag;
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  constructor(@Inject(PLATFORM_ID) private platformId: Object, public router: Router) {}

  ngOnInit() {
    const navEndEvent$ = this.router.events.pipe(filter(e => e instanceof NavigationEnd));
    navEndEvent$.subscribe((e: NavigationEnd) => {
      if (isPlatformBrowser(this.platformId)) {
        gtag('config', 'UA-xxxxxxxxx-x', { page_path: e.urlAfterRedirects });
      }
    });
  }
}

If you know more elegant solution or have any plans to improve the particular use case please let me know.

@AlexKopen
Copy link

Why not just include the gtag script in your header?

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants