2017-09-21 1 views
0

Je suis nouveau sur Google Analytics. Je suis en train d'essayer de mettre en œuvre Google Analytics à mon projet angulaire 2. Je l'ai mis en œuvre comme ci-dessous:Comment tester si le code google analytics fonctionne en angulaire 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); 
    } 

    } 

et 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> 

Can Quelqu'un me suggère-t-il cela?

Répondre

0

Créez simplement une nouvelle propriété dans Google Analytics et copiez l'UA-ID dans votre extrait index.html au ga('create', 'UA-XXXXXXXXX-X', 'auto');.

Here vous pouvez lire un bon article sur Angular et Google Analytics. Identique à l'auteur, je recommande fortement d'utiliser Google Tag Manager. Mais bien sûr, c'est aussi possible sans vous.

+0

yup c'est facile, mais je choisis [ceci] (https://blog.thecodecampus.de/angular-2-include-google-analytics-event-tracking/) on travaille. –