为Angular中的特定组件加载GA4脚本 我正在与Angular V12合作,构建一个将是使用不同客户端的用户的网页,我可以根据查询参数(REALM)(realm)判断客户端之间的区别,该网页是唯一的客户端,...

问题描述 投票:0回答:1
gtag.js

脚本,并专门为该领域获得测量ID,但是面对某些问题,例如Analytics(分析)无法链接数据。流到网页,(我认为这是因为它在为SEO添加元标记时不会在

index.html

中找到它 - 如果我错了,请纠正我 - )

这是

analytics.service.ts
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class AnalyticsService {
  private isLoaded = false;

  constructor() {}

  loadGoogleAnalytics(measurementId: string): void {
    console.log('hi loadGoogleAnalytics', measurementId);
    if (!measurementId || this.isLoaded) {
      return;
    }

    this.isLoaded = true;

    // Create script tag
    const script = document.createElement('script');
    script.async = true;
    script.src = `https://www.googletagmanager.com/gtag/js?id=${measurementId}`;
    document.head.appendChild(script);

    // Initialize GA
    script.onload = () => {
      (window as any).dataLayer = (window as any).dataLayer || [];
      function gtag(...args: any[]) {
        (window as any).dataLayer.push(args);
      }
      (window as any).gtag = gtag;

      gtag('js', new Date());
      gtag('config', measurementId);
      this.trackPageView();
    };
  }

  trackPageView(): void {
    console.log('Tracking page view:', window.location.hash);
    if ((window as any).gtag) {
      (window as any).gtag('event', 'page_view', {page_title: document.title, page_path: window.location.hash });
    }
  }  
}

那么解决此问题的建议解决方案是什么?
    

love,无论框架在DOM中正确外观,都应该从组件中加载GTAG。不,gtag不在乎是否没有index.html。为什么会呢?这是在浏览器中运行的前端脚本。您几乎可以在任何站点上加载并从控制台调用它。 google analytics test tag对我来说似乎是您可以再使用一些调试步骤。

SO使用GTAG。在此处打开DOM,查看GTAG是如何加载的。确保您的看起来相似。

确保您使用的是正确测量ID

。测量ID正是GA将数据链接到数据流的方式。
javascript angular google-analytics google-analytics-4
1个回答
0
投票
collect

端点。您也可以检查网络调用中的测量ID,但通常是DOM中的任何内容。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.