Ole*_*jko 3 html google-analytics typescript angular
我在尝试在angular2中实现谷歌分析时遇到了问题.根据我发现的信息,例如,在这篇文章中,它似乎很容易.但到目前为止,我没有找到任何例子,不是来自.html而是来自.ts.
我正在尝试使用谷歌分析制作私有方法,然后在构造函数中调用它.这样的事情.
constructor() {
this.initializeAnalytics();
}
private initializeAnalytics() {
(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', '//www.google-analytics.com/analytics.js', 'ga');
...
...
}
Run Code Online (Sandbox Code Playgroud)
但只是放置谷歌分析代码不起作用(错误:) supplied parameters do not match any signature of call target.我可能是以错误的方式做到这一点.
我怎么能做到这一点?
这就是我做到的.
您需要将ga代码放入index.html.(别忘了评论以下内容://ga('send', 'pageview');)
然后你需要在导入之后将ga函数声明到app.component.ts文件中:
import { ... } ...;
declare var ga:Function;
@component(...)
Run Code Online (Sandbox Code Playgroud)
然后您可以在app.component.ts中订阅路线更改事件并发送ga数据,如下所示:
this.router.events.subscribe((event:Event) => {
// Send GA tracking on NavigationEnd event. You may wish to add other
// logic here too or change which event to work with
if (event instanceof NavigationEnd) {
// When the route is '/', location.path actually returns ''.
let newRoute = this.location.path() || '/';
// If the route has changed, send the new route to analytics.
if (this.currentRoute != newRoute) {
ga('send', 'pageview', newRoute);
//console.log('would send to ga: ' + newRoute);
this.currentRoute = newRoute;
}
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6458 次 |
| 最近记录: |