import { Inject, inject, Injectable } from '@angular/core'; import { DOCUMENT } from '@angular/common'; import { environment } from '@environments/environment'; const { analyticsId } = environment; @Injectable({ providedIn: 'root', }) export class AnalyticsService { constructor(@Inject(DOCUMENT) private document: Document) {} setGtagUrl(url: string) { this.gtag('event', 'page_view', { page_title: url, page_path: url, }); } appendAnalyticsScript() { const window = this.document.defaultView as { [key: string]: any }; this.appendScript( `https://www.googletagmanager.com/gtag/js?id=${analyticsId}`, 'gtag', 'async' ); window['dataLayer'] = window['dataLayer'] || []; this.gtag('js', new Date()); this.gtag('config', analyticsId, { send_page_view: false }); } private appendScript(url: string, id: string, attr: 'async' | 'defer') { const existingScript = this.document.querySelector(`#${id}`); if (existingScript) { return existingScript; } const script = this.document.createElement('script'); script.setAttribute('src', url); script.setAttribute(attr, ''); script.id = id; this.document.head.appendChild(script); return script; } private gtag(...args: any[]) { (this.document.defaultView as { [key: string]: any })['dataLayer'].push(arguments); } } export const injectAnalyticsService = () => inject(AnalyticsService);