broadband
broadband

Reputation: 3498

Why Google Analytics sends two requests when user changes page in Angular?

I'm using Angular and put next code to index.html

<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXX"></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());
  gtag('config', 'G-XXXXX', {'send_page_view': false});
</script>

In my app.component I also added this, to track if page changes:

this.router.events.subscribe((event) => {
  if (event instanceof NavigationEnd) {
    (window as any).gtag('event', 'page_view', { path: event.urlAfterRedirects });
  }
});

I debbugged the code in Visual Studio and everything seems to be working ok. Data is received and displayed in Google Analytics Realtime section, but I'm curious is this ok for SPA applications to send 'page_view' event or should I always send 'config' event when user navigates to new page?

Another thing is, 2 requests are made to Google Analytics. The first one just after user navigates and the second a couple of seconds later:

enter image description here

Upvotes: 0

Views: 301

Answers (1)

BNazaruk
BNazaruk

Reputation: 8111

It's okay to always send pageviews on navigations on an SPA. You typically send configuration only on real page loads or when you want to change the standard set of fields (event parameters) to be included with every subsequent event.

Regarding your double call issue. It may or may not be okay. Check each call. Check the en parameter value. It stands for the event name. One of them has to be page_view. The other can be an auto event or another page_view. If it's the latter, then it looks like your NavigationEnd is being triggered twice. Or maybe you're sending the additional pageview from somewhere else. It's not ideal to have double pageviews. Probably won't hurt too much in your case, but it is still wrong enough to fix.

Upvotes: 1

Related Questions