angular 和 google 分析集成 => ga 不是函数

angular and google analytics integration => ga is not a function

我正在做一个 angular(4) 应用程序,但我在集成 google 分析时遇到了问题。 我目前要将 google 分析添加到我的单页 Web 应用程序中。但是当我尝试检索 ga 函数以发送新的 url 时,它似乎找不到该函数。

这是我得到的代码:

index.hbs

<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', 'My-key', 'auto');
</script>

app.component.ts

import { Component, OnInit } from '@angular/core';
import {NavigationEnd, Router} from "@angular/router";
import {WindowRef} from "./social/windowRef";
@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
})
export class AppComponent {
    user: User;
    private currentRoute: string;

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

windowRef.ts

export class WindowRef{
    public static get(): any{
        console.log(window);
        return window;
    }
}

我收到这个错误:ERROR TypeError: windowRef_1.WindowRef.get(...).ga is not a function

当我执行 console.log(WindowRef.get()); 时,我可以在 window 中看到 ga 函数,但是当我尝试使用它时它仍然显示之前的错误。 here and here

我不太明白我用这个方法来检索条带功能,效果很好。

祝你有美好的一天:)

我在尝试将 Google Analytics 集成到我的 Angular 4 应用程序时遇到了类似的问题。

我的诀窍是将 google 分析代码从 AppComponent 的构造函数移动到 ngAfterViewInit() 生命周期挂钩,以确保首先完全初始化视图。

这是我得到的代码:

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', 'some code', 'auto');
</script>

app.component.ts:

import {AfterViewInit, Component, Inject, PLATFORM_ID} from '@angular/core';
import {isPlatformBrowser} from '@angular/common';
import {NavigationEnd, Router} from '@angular/router';

// declare google analytics
declare const ga: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {

  constructor(@Inject(PLATFORM_ID) private platformId: Object,
              private router: Router) {}


  ngAfterViewInit(): void {
    this.router.events.subscribe(event => {
      // I check for isPlatformBrowser here because I'm using Angular Universal, you may not need it
      if (event instanceof NavigationEnd && isPlatformBrowser(this.platformId)) {
        console.log(ga); // Just to make sure it's actually the ga function
        ga('set', 'page', event.urlAfterRedirects);
        ga('send', 'pageview');
      }
    });
  }
}

让我知道这是否也适用于您。祝你今天过得愉快! :)

好的,我没有将 googleAnalytics 脚本放在正文之前,而是放在正文之后。现在效果很好。感谢@WeissDev,当我看到 ga 尽管在 window 中(很奇怪)但未定义时,它让我上路了。无论如何,他的解决方案也很有效。

如果@WeissDev 的回答对您不起作用,请在使用前使用 setInterval 确保其准备就绪。

  ngAfterViewInit() {
    this.initGoogleAnalyticsPageView()
  }

  private initGoogleAnalyticsPageView() {
    const interval = setInterval(() => {
      if ((window as any).ga && (window as any).ga.getAll) {
        this.router.events.subscribe(event => {
          const ga = (window as any).ga
          if (event instanceof NavigationEnd) {
            const tracker = ga.getAll()[0]
            tracker.set('page', event.urlAfterRedirects)
            tracker.send('pageview')
          }
        })
        clearInterval(interval)
      }
    }, 50)
  }

如果您访问 Analytics Google 网站,他们会这样说:

Copy the global site tag into the <head> section of your HTML. Or, if you use a website builder (e.g. WordPress, Shopify, etc), copy the global site tag into your website builder’s custom HTML field.

它需要进入 <head> 标签。