Integrating Google Analytics With Angular 2+

Publikováno: 27.2.2019

Requirements

For this tutorial, knowledge of HTML, CSS and JavaScript as well as some familiarity with Angular 2 development is expected. An understanding of Google analytics would be bene...

Celý článek

Requirements

For this tutorial, knowledge of HTML, CSS and JavaScript as well as some familiarity with Angular 2 development is expected. An understanding of Google analytics would be beneficial but is not absolutely necessary as it will be explained in the article.

Introduction

Google Analytics is at the forefront when it comes to offering effective ways to track the pages a user visits, the time he spends there and what he is doing. This makes it a necessity for the majority of companies around the world in providing valuable data for creating effective marketing campaigns, improving their user experience and so forth. Google Analytics goes even further to monitor the load times and accessibility of your site which gives you, as a developer, the ability to optimize your web application.

However, Google Analytics was designed with Multi- Page Applications in mind, because it calculates the number of page views by monitoring the navigation of users from one page to another. As Angular developers, we build Single Page Applications and this means our entire web app runs within one page which makes it hard for us to monitor user activity. Our application resources are dynamically loaded on the client side and this results in incorrect data being sent to our site tracker.

How do we fix this?

We need to emit an event every time we navigate through our application. We do this by using the Router.event to provide us with an observable that we can subscribe to and receive information we can send to our Google Analytics page. Well, let’s get started.

Register Your App on Google Analytics

First and foremost, we need to register our application with Google Analytics and get a Tracking ID. Go to the Google Analytics webpage and click sign in. This will show a drop down where we will click “Analytics”.

Click on the sign up button to go to the registration form where you will fill in the details about the web application. You then click the “Get Tracking ID” button and accept the terms and conditions. This will take you to your dashboard where you will see your new Tracking ID which you will use later.

Setup your Angular Application

We will be using the Angular CLI for this example. If you do not have the Angular CLI installed on your computer, run the following command.

 npm install -g @angular/cli

Now create your new project.

ng new angularGoogleAnalytics

Our application is still empty and as a result we cannot yet track a user activity. We need to generate two new components i.e. component-1 and component-2 that we will navigate between.

ng g component component-1
ng g component component-2

Now that we have our two components, we need to set up our router such that we can navigate between them. This is what we will track with Google Analytics. In our app.module.ts, import the RouterModule and set up our routes.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router'; //Import the Angular router module and Routes

import { AppComponent } from './app.component';
import { Component1Component } from './component-1/component-1.component';
import { Component2Component } from './component-2/component-2.component';

export const appRoutes: Routes = [
  {path: '', component: Component1Component},
  {path: 'component-2', component: Component2Component}
];

@NgModule({
  declarations: [
    AppComponent,
    Component1Component,
    Component2Component
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(appRoutes),
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Once this is done, add a router outlet to our app.component.html file to output our different components.

<router-outlet></router-outlet>

Add the Google Analytics Tracking Code

You now have an Angular app with two components that you can navigate easily between. It is now time to add our Google Analytics code to track the user activity. We do this by adding the tracking code into our index.html file. However, since we are building a single page application, we must send our page views manually and therefore, we remove the ga('send', 'pageview');line, which is responsible for transmitting the page views, from our code.

<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-xxxxx-xxx', 'auto');  // Change the UA-ID to the one you got from Google Analytics

  </script>

To manually send our page views to Google Analytics, we import the Router and NavigationEnd from @angular/router into our app.component.ts. We then subscribe to the router.events property to trigger a page view when we move from one route to another.

import { Component } from '@angular/core';
import {Router, NavigationEnd} from '@angular/router'; // import Router and NavigationEnd

  // declare ga as a function to set and sent the events
 declare let ga: Function;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {

  title = 'app';

   constructor(public router: Router) {

    // subscribe to router events and send page views to Google Analytics
    this.router.events.subscribe(event => {

      if (event instanceof NavigationEnd) {
        ga('set', 'page', event.urlAfterRedirects);
        ga('send', 'pageview');

      }

    });
  }

}

Now we need to create links to navigate between our components. Add the following router link to your component-1.component.html file to navigate to component-2.

<p>
  component-1 works!
</p>

<button type="button" class="btn btn-primary" routerLink="/component-2">Go To Component 2</button>

Add another router link to component-2.component.html to navigate back to component-1.

<button type="button" class="btn btn-primary" routerLink="/">Go To Component 1</button>

Now serve your application, go to http://localhost:4200 and move fromcomponent-1 to component-2.

https://vimeo.com/319541067

Congratulations, you can now track the different pages a user visits when he accesses your website.

Add Event Tracking

We may want to do more than just track a users page visits on a site. Using a real world example of a picture sharing app, we may want to track when a user clicks the like button on a particular photo and why. We do this by creating a service with an event emitter that takes in the eventCategory, eventAction, eventLabel as well as eventValue and submits it to Google Analytics.

import { Injectable } from '@angular/core';

declare let ga:Function; // Declare ga as a function

@Injectable()
export class GoogleAnalyticsService {

  constructor() { }

  //create our event emitter to send our data to Google Analytics
   public eventEmitter(eventCategory: string,
                   eventAction: string,
                   eventLabel: string = null,
                   eventValue: number = null) {
    ga('send', 'event', {
      eventCategory: eventCategory,
      eventLabel: eventLabel,
      eventAction: eventAction,
      eventValue: eventValue
    });

                   }

}

We then import our service to the app.module.ts file and add it as a provider.

import {GoogleAnalyticsService} from "./google-analytics.service"; // import our Google Analytics service

providers: [GoogleAnalyticsService], //add it as a provider

Assuming that our component-2 is a page where a user has shared a picture, we add an image and a like button to the component-2.component.html. Our like button, will have a click event that triggers the sendLikeEvent() function.

<div class = "row" style="padding-top:150px;">
  <div class = "col-md-5 offset-3 text-center">

    <img src="assets/man-1352025_960_720.png" width="500px" height="300px" style="padding-bottom:30px;"><br/>
    <button type="button" class="btn btn-primary btn-lg center" (click)="SendLikeEvent()">Like</button>

  </div>
</div>

In the component-2.component.ts file, we import our GoogleAnalyticsService and add it to our sendLikeEvent() function. This will pass our eventCategory, eventAction, eventLabel and eventValue details to our service which will submit them to Google Analytics.

import { Component, OnInit } from '@angular/core';
import {GoogleAnalyticsService} from "../google-analytics.service"; // import our analytics service

@Component({
  selector: 'app-component-2',
  templateUrl: './component-2.component.html',
  styleUrls: ['./component-2.component.css']
})
export class Component2Component implements OnInit {

  constructor(public googleAnalyticsService: GoogleAnalyticsService) { }

  ngOnInit() {
  }

  SendLikeEvent() {
    //We call the event emmiter function from our service and pass in the details
    this.googleAnalyticsService.eventEmitter("userPage", "like", "userLabel", 1);
  }

}

Now go to your browser and click the like button on your component-2 page.

Check your Google Analytics Dashboard’s real time event tracker and you will see the values we passed in from our component-2.

Congratulations, you are now also able to track user events on your web application.

Conclusion

Google Analytics is a great tool for tracking user activity and we have seen how it integrates into an Angular application to track page views and events. We have also seen a small example of how events tracking could be used and I hope that this has given you a few ideas on how you could integrate it into your own projects and use that data to optimize, market and evolve.

I hope you have enjoyed this article and remember to always keep learning.

Nahoru
Tento web používá k poskytování služeb a analýze návštěvnosti soubory cookie. Používáním tohoto webu s tímto souhlasíte. Další informace