Introduction

Google Analytics is a tool that helps you keep track of your User Activity. This includes how many users entered your website in a specific time-span, where those users came from, which pages they visited, etc. It has even expanded to how well your site’s speed is doing and how much social signal your site has garnered.

In short, Google Analytics is all about real data in your website. Data that you can translate into useful business intelligence and SEO strategy for your online campaigns.

The Challenge

Google Analytics works well in MPAs (Multi-Page Applications). When a user navigates to the other pages of a website, Google Analytics code triggers a pageview event using a simple code which is provided by Google. This enables you to calculate the number of views a particular page of the website has. In the case of SPAs (Single Page Applications), It has only one page (index.html). It’s difficult to track users page visits because there is no page request from the server all appropriate resources are dynamically loaded and added to the page as necessary, usually in response to user actions. This results in inaccurate page visits data because routes navigation in SPAs does not perform a full server request, so a pageview event is not triggered.

The Solution

Angular provides a module Router that enables navigation from one view to the next. During each navigation, the Router emits navigation events through the Router.events property. These events range from when the navigation starts and ends to many points in between.Since the events are provided as an Observable , you can filter() for events of interest and subscribe() to them to make decisions based on the sequence of events in the navigation process.

To solve the Google Analytics problem in Angular (SPA), we subscribe to the Router events observable and send the pageview event to Google Analytics when a router event is emitted.

In this article, we are going to see how to track page visits in Angular by subscribing to Router events observable.

Hands in the Mud

So let’s get our hands dirty. Before we start, let’s first create and register our app in Google Analytics website.

Step 1: Goto http://www.google.com/analytics/