我用Angular 2作为前端构建了一个新站点.由于所有操作都是通过push state完成的,因此没有页面加载通常会触发Google Analytics代码将页面视图发送到Google的服务器.
我怎样才能手动将页面浏览事件发送到谷歌,以便跟踪我的网站的哪些用户正在浏览?
我用Angular 2作为前端构建了一个新站点.由于所有操作都是通过push state完成的,因此没有页面加载通常会触发Google Analytics代码将页面视图发送到Google的服务器.
我怎样才能手动将页面浏览事件发送到谷歌,以便跟踪我的网站的哪些用户正在浏览?
我通过订阅路由上的更改,判断路由是否确实更改了(我有时会在某些路由上收到多个事件),然后将新路径发送到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脚本中删除以下行
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>
Using a third party library
作为自己实现GA的替代方案,library Angulartics2也是实现GA跟踪的流行工具,还与其他分析供应商集成.