使用Google Analytics的Angular 4+ [英] Angular 4+ using Google Analytics

查看:241
本文介绍了使用Google Analytics的Angular 4+的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用angular 4来使用Google Analytics,但在ts中我找不到任何@type到ga.js。



解决方案我在每个组件中都使用了它:

  declare let ga:any; 

按照我的解决方法:

创建一个动态加载GA的函数,该GA插入带有当前trackingId和用户的GA脚本。

  loadGA(userId){
if(!environment.GAtrackingId)return;

让scriptId ='google-analytics';

if(document.getElementById(scriptId)){
return;
}

var s = document.createElement('script')as any;
s.type =text / javascript;
s.id = scriptId;
s.innerText =(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),米= s.getElementsByTagName(O)[0]; a.async = 1; a.src =克; m.parentNode.insertBefore(A,M)})(窗口,文件, '脚本',// WWW。 google-analytics.com/analytics.js','ga');ga('create',{trackingId:'+ ** environment.GAtrackingId ** +',cookieDomain:'auto',userId:'+ ** userId ** +'}); ga('send','pageview','/');;

document.getElementsByTagName(head)[0] .appendChild(s);
}

创建服务以实现您将需要的方法。

 从'@ angular / core'导入{Injectable}; 
从'../../../environments/environment'导入{environment};

申报让ga:any;

@Injectable()
导出类GAService {
构造函数(){
}
$ b $ / **
*支票如果GA脚本已加载。
* /
private useGA():boolean {
return environment.GAtrackingId&& typeof ga!==未定义;
}

/ **
*将页面视图发送给GA。
* @param {string}页面URL的路径部分。该值应以斜杠(/)字符开头。
* /
sendPageView(
page:string
){
if(!this.useGA())return;
if(!page.startsWith('/'))page =`/ $ {page}`;
ga('send','pageview',page);
}


/ **
*将活动发送给GA。
* @param {string} eventCategory通常与之交互的对象(例如'Video')
* @param {string} eventAction交互类型(例如'play')
* /
sendEvent(
eventCategory:string,
eventAction:string
){
if(!this.useGA())return;
ga('send','event',eventCategory,eventAction);
}
}

然后我最终使用注入组件的服务。 / p>

 构造函数(private ga:GAService){} 

ngOnInit(){this.ga.sendPageView '/加入'); }


解决方案

首先,您需要安装typings Google Analytics在您的 devDependencies中

  npm install --save-dev @类型/ google.analytics 

然后将您的跟踪代码添加到基本索引中。 html ,然后移除最后一行,如下图所示:

 < body> 
< app-root>正在加载...< / app-root>
< 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-XXXXXX-ID','auto'); //< - 添加UA-ID
//< - 删除最后一行
< / script>
< / body>

下一步是更新您的主件组件构造函数以进行事件跟踪。

 构造函数(public router:Router){
this.router.events.subscribe(event => {
if(事件instanceof NavigationEnd){
ga('set','page',event.urlAfterRedirects);
ga('send','pageview');
}
});

$ / code>

如果您想跟踪某个特定事件,您也可以创建一个服务并将其注入到要实现事件跟踪的任何组件中。

  // ./src/app/services/google-analytics-events-service.ts 

从@ angular / core导入{Injectable};

@Injectable()
导出类GoogleAnalyticsEventsService {

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




$ b $ p
$ b $ p所以如果你想跟踪你的家庭组件例如,您只需注入 GoogleAnalyticsEventsService 并调用 emitEvent()方法即可。

更新后的home组件源代码:

 构造函数(公共路由器:路由器,公共googleAnalyticsEventsService:GoogleAnalyticsEventsService){
this.router.events.subscribe(event => {
if(event instanceof NavigationEnd){
ga('set','page' ,event.urlAfterRedirects);
ga('send','pageview');
}
});

submitEvent(){//从home.component.html元素触发事件(按钮,链接,...)
this.googleAnalyticsEventsService.emitEvent(testCategory,testAction ,testLabel,10);
}


I'm trying to use the Google Analytics with angular 4, but i can't find any @type to ga.js in ts.

For a quick solution I used this in every component:

declare let ga: any;

Following how I resolved it:

Create a function to load the GA dynamically that inserts the GA script with current trackingId and user.

    loadGA(userId) {
        if (!environment.GAtrackingId) return;

        let scriptId = 'google-analytics';

        if (document.getElementById(scriptId)) {
            return;
        }

        var s = document.createElement('script') as any;
        s.type = "text/javascript";
        s.id = scriptId;
        s.innerText = "(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');ga('create', { trackingId: '" + **environment.GAtrackingId** + "', cookieDomain: 'auto', userId: '" + **userId** + "'});ga('send', 'pageview', '/');";

        document.getElementsByTagName("head")[0].appendChild(s);
    }

Create the service to implement the methods that you will need.

import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';

declare let ga: any;

@Injectable()
export class GAService {
    constructor() {
    }

    /**
     * Checks if the GA script was loaded.
     */
    private useGA() : boolean { 
        return environment.GAtrackingId && typeof ga !== undefined;
    }

    /**
     * Sends the page view to GA.
     * @param  {string} page The path portion of a URL. This value should start with a slash (/) character.
     */
    sendPageView(
        page: string
    ) {
        if (!this.useGA()) return;
        if (!page.startsWith('/')) page = `/${page}`;      
        ga('send', 'pageview', page);
    }


    /**
     * Sends the event to GA.
     * @param  {string} eventCategory Typically the object that was interacted with (e.g. 'Video')
     * @param  {string} eventAction The type of interaction (e.g. 'play')
     */
    sendEvent(
        eventCategory: string,
        eventAction: string
    ) { 
        if (!this.useGA()) return;
        ga('send', 'event', eventCategory, eventAction);
    }
}

Then I finally use the service injected in component.

constructor(private ga: GAService) {}

ngOnInit() { this.ga.sendPageView('/join'); }

解决方案

First of all, you need to install typings for Google Analytics in your devDependencies

npm install --save-dev @types/google.analytics

Then add your tracking code in the base index.html, and remove the last line as shown bellow:

<body>
  <app-root>Loading...</app-root>
  <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-XXXXXX-ID', 'auto');  // <- add the UA-ID 
                                           // <- remove the last line 
  </script>
</body>

The next step consists to update your home component constructor for event tracking.

constructor(public router: Router) {
    this.router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        ga('set', 'page', event.urlAfterRedirects);
        ga('send', 'pageview');
      }
    });
  }

If you want to track some specific event, you can also create a service and inject it into any component that you want to implement event tracking.

// ./src/app/services/google-analytics-events-service.ts

import {Injectable} from "@angular/core";

@Injectable()
export class GoogleAnalyticsEventsService {

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

So if you want track a click on your home component for example, all you need to do is to inject the GoogleAnalyticsEventsService and call the emitEvent() method.

The updated home component source code:

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() { // event fired from home.component.html element (button, link, ... )
    this.googleAnalyticsEventsService.emitEvent("testCategory", "testAction", "testLabel", 10);
  }

这篇关于使用Google Analytics的Angular 4+的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆