2017-09-21 39 views
0

我是Google Analytics(分析)新手。我正在嘗試將Google分析應用於我的angular 2項目。我已經實現象下面這樣:如何測試谷歌分析代碼是否在角度2中工作?

app.component.ts

import { Component } from '@angular/core'; 
import {Router, NavigationEnd} from "@angular/router"; 
import {GoogleAnalyticsEventsService} from "./google-analytics-events.service"; 
declare var ga:Function; 
@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'] 
}) 
export class AppComponent { 

    onSubmit = function(login){ 
     console.log(login); 
    } 
    constructor(public router: Router, public googleAnalyticsEventsService: GoogleAnalyticsEventsService) { 
    this.router.events.subscribe(event => { 
     if (event instanceof NavigationEnd) { 
     ga('set', 'page', event.urlAfterRedirects); 
     ga('send', 'pageview'); 
     } 
    }); 
    } 
    submitEvent() { 
     this.googleAnalyticsEventsService.emitEvent("testCategory", "testAction", "testLabel", 10); 
    } 

    } 

以及Google Analytics(分析),events.service.ts

import {Injectable} from "@angular/core"; 
declare var ga:Function; 
@Injectable() 
export class GoogleAnalyticsEventsService { 

    public emitEvent(eventCategory: string, 
       eventAction: string, 
       eventLabel: string = null, 
       eventValue: number = null) { 
    ga('send', 'event', { 
     eventCategory: eventCategory, 
     eventLabel: eventLabel, 
     eventAction: eventAction, 
     eventValue: eventValue 
    }); 
    } 
} 

的index.html

<script> 
    (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','https://www.google-analytics.com/analytics.js','ga'); 

    ga('create', 'UA-XXXXXXXXX-X', 'auto'); 
    ga('send', 'pageview'); 
</script> 

燦任何人在這個建議我?

回答

0

只需在Google Analytics中創建一個新媒體資源,然後將UA-ID複製到您的index.html片段ga('create', 'UA-XXXXXXXXX-X', 'auto');

Here你可以閱讀一篇關於Angular和Google Analytics的好文章。與作者相同,我強烈建議您使用Google跟蹤代碼管理器。但是,當然也可能沒有像你這樣做。

+0

這很容易,但我選擇[this](https://blog.thecodecampus.de/angular-2-include-google-analytics-event-tracking/)一個工程。 –