我使用Angular 2作为前端构建了一个新站点。由于一切都是通过推送状态完成的,因此没有页面加载通常会触发Google Analytics代码将页面视图发送到Google的服务器。
如何手动向Google发送网页浏览事件,以便跟踪我网站的哪些用户正在查看?
答案 0 :(得分:53)
我设法通过订阅路由器上的更改,检查路由实际已更改(我有时在某些路由上获得多个事件)然后将新路径发送给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 Analytics代码,以便存在全局ga
对象,但您不希望两次发送初始视图。为此,请从GA脚本中删除以下行
<强>的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跟踪的流行工具,也可以与其他分析供应商集成。
答案 1 :(得分:33)
扩展伊恩的答案。您可以使用Rx的内置功能来处理当前路由和新路由之间的区别。
import { NavigationEnd, Router } from '@angular/router';
declare var ga: any;
export class AppComponent {
constructor(public router: Router) {
router.events.distinctUntilChanged((previous: any, current: any) => {
if(current instanceof NavigationEnd) {
return previous.url === current.url;
}
return true;
}).subscribe((x: any) => {
console.log('router.change', x);
ga('send', 'pageview', x.url);
});
}
}
我们使用distinctUntilChanged运算符使观察者只发出NavigationEnd类型的项目,并且没有与先前发出的项目相同的路由。
答案 2 :(得分:20)
如果您在2017年8月之后遇到此问题 ,那么您很可能应该使用gtag.js(Google Universal Analytics全球网站代码)而不是旧analytics.js。我建议您在继续之前检查Migrate from analytics.js to gtag.js页面和How gtag.js works in Single page applications之间的差异。
当您从Google Analytics获取代码段时,它看起来像这样:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=<%= GOOGLE_ANALYTICS_ID %>"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '<%= GOOGLE_ANALYTICS_ID %>'); <!-- Remove that one -->
</script>
您需要删除脚本的最后一行,然后将其余部分添加到index.html
。
然后,您必须将从上面脚本中删除的行添加到代码中,并将该页面添加到跟踪。基本上它与上面为analytics.js
建议的人几乎相同,但现在你使用gtag.js
函数。
例如,如果您想跟踪您在此处打开的所有页面,请参阅示例代码:
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import 'rxjs/add/operator/distinctUntilChanged';
// This still has to be declared
declare var gtag: Function;
@Component({
moduleId: module.id,
selector: 'my-app',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css'],
})
export class AppComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() {
this.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) => {
gtag('config', '<%= GOOGLE_ANALYTICS_ID %>', {'page_path': x.url});
});
}
}
如果您已阅读gtag.js
的文档,那么您就会知道可能有大量的跟踪选项,但我会专注于此处的最基本用法。
答案 3 :(得分:1)
在Angular 6中,我建议使用app.component.ts:
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router'
import { Title } from '@angular/platform-browser';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(
private router: Router,
private titleService: Title
){ }
ngOnInit() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
(<any>window).gtag('config', '<%= GOOGLE_ANALYTICS_ID %>', {
'page_title' : this.titleService.getTitle(),
'page_path': event.urlAfterRedirects
});
}
});
}
}
对于index.html:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=<%= GOOGLE_ANALYTICS_ID %>"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
</script>
您可以使用Angular提供的“标题”服务来管理页面的标题:https://angular.io/guide/set-document-title
答案 4 :(得分:0)
假设每个Angular Route在app.routing.ts
中都有自己的标题:
{
path: 'shop',
component: ShopComponent,
data: {
title: ' == This is Shop Component Title =='
},
canActivate: [AuthGuard]
},
前面提到的解决方案仍将在Google Analytics(分析)报告中为每条路线显示相同的页面标题。为了利用相应的Angular Route标题(而不是始终使用index.html <title>
标签内容),请使用以下app.component.ts
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
(<any>window).ga('set', 'page', event.urlAfterRedirects);
// ----------
//use the following 3 lines of code to use
//correnct titles for routes
// ----------
let currentRoute = this.route.root;
let title = this.getPageTitle(currentRoute);
(<any>window).ga('set', 'title', title);
(<any>window).ga('send', 'pageview');
}
});
...其中getPageTitle
方法如下:
getPageTitle = function (currentRoute: ActivatedRoute) {
let data;
do {
const childrenRoutes = currentRoute.children;
currentRoute = null;
childrenRoutes.forEach(route => {
if (route.outlet === 'primary') {
currentRoute = route;
data = route.snapshot.data;
}
});
} while (currentRoute);
return data.title;
};
注意:此解决方案适用于Anguler 5及以下版本。在Angular 6中,您还可以使用TitleService
答案 5 :(得分:0)
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
ga('set','page', event.urlAfterRedirects);
ga('send', 'pageview');
}
});