2016-11-21 3 views
2

私はangular2でgoogle analyticsを実装しようとすると問題が発生しました。 私が見つけた情報によれば、例として、this postではかなり簡単です。しかしこれまでのところ、私はどのようにして.htmlからではなく、.tsからではなく、どのようにそれを行うかの例を見出しませんでした。Angular2でGoogle Analyticsを実装するにはどうすればよいですか?

Googleアナリティクスでプライベートメソッドを作成し、それをコンストラクタで呼び出そうとしています。そんな感じ。

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

    ... 
    ... 
} 

Googleアナリティクスコードを配置するだけでは機能しません(エラー:supplied parameters do not match any signature of call target)。私はおそらく間違った方法でそれをやっています。

どうすればこの問題を解決できますか?

答えて

5

これは私のやり方です。

あなたのindex.htmlにガコードを入れる必要があります。 (以下の行をコメントするのを忘れないでください):

次に、インポート後にapp.component.tsファイルにga関数を宣言する必要があります。

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) 

の機能は、しかし、あなただけのこの行に5を供給し、7非オプションのパラメータがあります。

(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'); 
関連する問題