在 Angular2 中跟踪 Google Analytics(分析)页面浏览量 [英] Tracking Google Analytics Page Views in Angular2

查看:15
本文介绍了在 Angular2 中跟踪 Google Analytics(分析)页面浏览量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Angular 2 作为前端构建了一个新站点.由于一切都是通过推送状态完成的,因此没有页面加载通常会触发 Google Analytics 代码将页面浏览发送到 Google 的服务器.

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.

如何手动向 Google 发送页面查看事件,以便跟踪我网站的用户正在查看的内容?

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

推荐答案

我通过订阅路由器上的更改,检查路由是否实际发生了更改(我有时在某些路由上收到多个事件),设法使其工作然后将新路径发送给 Google.

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

import { ... } from '...';

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

@Component({ ... })

export class AppComponent {
    private currentRoute:string;

    constructor(_router:Router) {
        // Using Rx's built in `distinctUntilChanged ` feature to handle url change c/o @dloomb's answer
        router.events.distinctUntilChanged((previous: any, current: any) => {
            // Subscribe to any `NavigationEnd` events where the url has changed
            if(current instanceof NavigationEnd) {
                return previous.url === current.url;
            }
            return true;
        }).subscribe((x: any) => {
            ga('set', 'page', x.url);
            ga('send', 'pageview')
        });
      }
    }
}

在加载 angular2 应用程序之前,您还需要在主索引文件中包含 google 分析代码,以便全局 ga 对象存在,但您不想发送两次初始视图.为此,请从 GA 脚本中删除以下行

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>

<小时>

使用第三方库

作为自己实施 GA 的替代方法,库 Angulartics2 也是实施 GA 跟踪的流行工具并且还与其他分析供应商集成.

As an alternative to implementing GA yourself, the library Angulartics2 is also a popular tool for implementing GA tracking and also integrates with other analytics vendors as well.

这篇关于在 Angular2 中跟踪 Google Analytics(分析)页面浏览量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆