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 });
}
}
}
那么解决此问题的建议解决方案是什么?
SO使用GTAG。在此处打开DOM,查看GTAG是如何加载的。确保您的看起来相似。
确保您使用的是正确测量ID
。测量ID正是GA将数据链接到数据流的方式。collect
端点。您也可以检查网络调用中的测量ID,但通常是DOM中的任何内容。