1

I want to implement Google analytics for an Angular SPA which is currently running in my localhost. I tried to copy the google tracking Js code to each of my view in the Angular SPA. But i don't think it actually worked.

Is this the correct way to implement Google Analytics or whats the correct way?

<div class="background">
    <div class="container">
        <h2 class="page-title">{{'contact-name' | translate}}</h2>
    </div>
</div>
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-XXXXXXXX-Y', 'auto');
  ga('send', 'pageview');

</script>
Varun
  • 3,695
  • 6
  • 21
  • 34

1 Answers1

2

Don't insert the script in each of your views, instead paste it within your main HTML page. In addition to Google Analytics you might want to consider using Autotrack and the urlChangeTracker in your SPA

t3__rry
  • 2,817
  • 2
  • 23
  • 38
  • Thanks, i'll try that. I'm currently running my application on my local machine and running at localhost:3000. Will i get any results in GA if i use the URL while setting up as other than localhost:3000, because localhost is invalid at the URL. – Varun Sep 26 '16 at 21:25
  • 1
    I've found this post to help you getting started: http://stackoverflow.com/questions/30581916/test-google-analytics-on-localhost – t3__rry Sep 27 '16 at 11:32
  • Hey, that helped, thanks. If you have any small code snippet on how Autotrack is being used for Single Page App, can you share that. I'm really confused on where to implement the tracking snippet code. – Varun Sep 27 '16 at 17:16
  • Insert the script at the bottom of your body tag just like you did with your Google Analytics script: ` More infos in the docs: https://github.com/googleanalytics/autotrack#installation-and-usage – t3__rry Sep 27 '16 at 17:32
  • hey, could you please refer to this post and help me solve my problem. http://stackoverflow.com/questions/39731697/google-analytics-on-spa-cant-get-url-changes – Varun Sep 27 '16 at 18:19