将Google Analytics(分析)与Angular 2+集成

要求 ( 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.

对于本教程,期望掌握HTML,CSS和JavaScript知识,并对Angular 2开发有所了解。 对Google Analytics(分析)的了解将是有益的,但并非绝对必要,因为本文将对此进行解释。

介绍 ( 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.

在提供有效的方法来跟踪用户访问的页面,用户在此花费的时间以及他在做什么方面,Google Analytics(分析)处于最前沿。 这使得全球大多数公司都有必要提供有价值的数据,以进行有效的营销活动,改善用户体验等。 Google Analytics(分析)甚至可以监视网站的加载时间和可访问性,从而使您(作为开发人员)能够优化您的Web应用程序。

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.

但是,Google Analytics(分析)在设计时考虑了多页面应用程序,因为它通过监视用户从一页到另一页的导航来计算页面浏览量。 作为Angular开发人员,我们构建单页应用程序,这意味着我们的整个Web应用程序都在一页内运行,这使我们难以监视用户活动。 我们的应用程序资源是在客户端动态加载的,这导致将错误的数据发送到我们的网站跟踪器。

我们该如何解决? ( 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.

每次在应用程序中导航时,我们都需要发出一个事件。 为此,我们使用Router.event向我们提供了一个可观察的对象,我们可以订阅它并接收可以发送到Google Analytics(分析)页面的信息。 好吧,让我们开始吧。

在Google Analytics(分析)上注册您的应用 ( 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”.

首先,我们需要在Google Analytics(分析)中注册我们的应用程序并获取跟踪ID。 转到Google Analytics(分析)网页,然后单击“登录”。这将显示一个下拉列表,单击“ 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.

单击注册按钮转到注册表单,您将在其中填写有关Web应用程序的详细信息。 然后,您单击“获取跟踪ID”按钮并接受条款。 这将带您到仪表板,您将在其中看到新的跟踪ID,以后将使用它。

设置您的Angular应用程序 ( 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.

在此示例中,我们将使用Angular CLI。 如果您的计算机上未安装Angular CLI,请运行以下命令。

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.

我们的应用程序仍然是空的,因此我们还无法跟踪用户活动。 我们需要生成两个新的组件,即组件1和组件2,我们将在它们之间进行导航。

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.

现在我们有了两个组件,我们需要设置路由器,以便可以在它们之间导航。 这就是我们将使用Google Analytics(分析)跟踪的内容。 在我们的app.module.ts ,导入RouterModule并设置我们的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.

完成此操作后,将路由器出口添加到我们的app.component.html文件中以输出我们的不同组件。

<router-outlet></router-outlet>

添加Google Analytics(分析)跟踪代码 ( 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.

现在,您将拥有一个包含两个组件的Angular应用程序,您可以在两个组件之间轻松导航。 现在是时候添加我们的Google Analytics(分析)代码来跟踪用户活动了。 为此,我们将跟踪代码添加到我们的index.html文件中。 但是,由于我们正在构建单个页面应用程序,因此必须手动发送页面视图,因此,我们删除了ga('send', 'pageview'); 行,负责从我们的代码中传输页面浏览量。

<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.

要将页面浏览量手动发送到Google Analytics(分析),我们将RouterNavigationEnd@angular/router导入到app.component.ts 。 然后,当从一条路由移动到另一条路由时,我们订阅了router.events属性以触发页面视图。

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.

现在,我们需要创建链接以在我们的组件之间导航。 将以下路由器链接添加到component-1.component.html文件中,以导航到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.

将另一个路由器链接添加到component-2.component.html以导航回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.

现在为您的应用程序提供服务,请访问http:// localhost:4200,然后从component-1移至component-2

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.

我们可能要做的不仅仅是跟踪用户在网站上的页面访问。 使用图片共享应用程序的真实示例,我们可能希望跟踪用户何时单击特定照片上的“赞”按钮以及原因。 为此,我们创建了一个带有事件发射器的服务,该服务接收了eventCategoryeventActioneventLabel以及eventValue并将其提交给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.

然后,我们将服务导入到app.module.ts文件中,并将其添加为提供程序。

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.

假设我们的component-2是用户共享图片的页面,我们向component-2.component.html添加一个图像和一个component-2.component.html按钮。 我们的like按钮将具有一个click事件,该事件触发sendLikeEvent()函数。

<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.

component-2.component.ts file ,我们导入GoogleAnalyticsService并将其添加到sendLikeEvent()函数中。 这会将我们的eventCategory, eventAction, eventLabeleventValue详细信息传递给我们的服务,并将其提交给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.

现在转到浏览器,然后在component-2页面上单击like按钮。

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

检查您的Google Analytics(分析)仪表板的实时事件跟踪器,您将看到我们从component-2传入的值。

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

恭喜,您现在也可以跟踪Web应用程序上的用户事件。

结论 ( 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.

Google Analytics(分析)是跟踪用户活动的好工具,我们已经看到了它如何集成到Angular应用程序中以跟踪页面视图和事件。 我们还看到了一个有关如何使用事件跟踪的小例子,我希望这为您提供了一些有关如何将其集成到自己的项目中以及如何使用该数据进行优化,营销和发展的想法。

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

希望您喜欢这篇文章,并记住始终学习。

翻译自: https://scotch.io/tutorials/integrating-google-analytics-with-angular-2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值