2016-11-21 50 views
2

我在尝试在angular2中实施谷歌分析时遇到了问题。 根据我找到的信息和例子,在this post看起来很容易。但到目前为止,我没有找到任何示例如何做,而不是从.html,而是从.ts如何在Angular2中实现Google Analytics?

我想用谷歌分析一个私人的方法,然后在构造函数中调用它。类似的东西。

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'); 

    ... 
    ... 
} 

但只是放置谷歌分析代码不起作用(错误:supplied parameters do not match any signature of call target)。我可能是以错误的方式来做。

我该如何做到这一点?

回答

5

这就是我做到的。

您需要将ga代码放入index.html。 (不要忘记评论以下行:// ga('send','pageview');)

然后,您需要在导入之后将ga函数声明到app.component.ts文件中:

import { ... } ...; 

declare var ga:Function; 

@component(...) 

然后,你可以订阅你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; 
     } 
    } 
}); 
+0

感谢的答案,但是这正是我发现同样的事情(表链接的URL) –

1

您需要的代码转换打字稿。目前它是Javascript。在

function (i, s, o, g, r, a, m) 

函数有7个非可选参数,但是你只在这一行提供5:

(window, document, 'script', '//www.google-analytics.com/analytics.js', 'ga') 

你需要做的其余参数可选,像这样:

function (i, s, o, g, r, a?, m?) 

然后,您还需要更改不同的行:

}, i[r].l = 1 * new Date(); 

}, i[r].l = 1 * <any>new Date(); 

最后的代码看起来是这样的:

(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 * <any>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'); 
相关问题