Ian Belcher Ian Belcher - 4 months ago 456
Javascript Question

Tracking Google Analytics Page Views in Angular2

I have built a new site using Angular 2 as the front-end. As everything is done via push state, there are no page loads which typically trigger the Google Analytics code to send a page view to Google's servers.

How can I manually send page view events to Google so that I can track what users of my site are viewing?

Answer

I managed to get this working by subscribing to changes on the router, checking that the route had actually changed (I was getting multiple events on some routes at times) and then sending the new path to Google.

app.component.ts

// Declare ga function as ambient
declare var ga:Function;

export class AppComponent {
    private currentRoute:string;

    constructor(_router:Router) {
        // This subscribe is for the rc1 router. For `router-deprecated` use `_router.subscribe` instead.
        _router.changes.subscribe(() => {
            // When the route is '/', location.path actually returns ''.
            let newRoute = this._location.path() || '/';
            // If the route has changed, send the new route to analytics.
            if (this.currentRoute != newRoute) {
                ga('send', 'pageview', newRoute);
                this.currentRoute = newRoute;
            }
        });
    }
}

You also need to include the google analytics code in your main index file before loading your angular2 app so that the global ga object exists, but you don't want to send the initial view twice. In order to do this, remove the following line from the GA script

index.html

<script>
  (function(i,s,o,g,r,a,m){...})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-XXXXXXXX-X', 'auto');
  // Remove this line to avoid sending the first page view twice.
  //ga('send', 'pageview');

</script>
<!-- 
    Load your ng2 app after ga. 
    This style of deferred script loading doesn't guarantee this will happen
    but you can use Promise's or what works for your particular project. 
-->
<script defer type="text/javascript" src="/app.js"></script>
Comments