import { Observable, throwError } from 'rxjs'; import { Inject, Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'; import { IAppConstants } from '../helpers/constants/app-constants.interface'; import { AppConstants } from '../helpers/constants/app.constants'; import {} from '../helpers/extension/global.extensions'; import { ScriptService } from '../helpers/script/script.helper'; import { GlobalDataService } from './global-data.service'; @Injectable() export class GoogleTagManagerService { private baseUrl: string; constructor( private http: HttpClient, private globalData: GlobalDataService, @Inject(AppConstants) private constants: IAppConstants, private scriptService: ScriptService ) { this.baseUrl = this.globalData.BaseUrl; } private get googleTagManagerSettingsUrl() { return `${this.baseUrl}${this.constants.ARTICLES_API_ROUTE_PREFIX}${this.constants.GOOGLE_TAG_MANAGER_SETTINGS_URL}`; } protected getRequestHeaders(): { headers: HttpHeaders | { [header: string]: string | string[] }; } { const headers = { headers: new HttpHeaders({ 'Content-Type': 'application/json', Accept: 'application/json', 'Cache-Control': 'no-cache', Pragma: 'no-cache' }), withCredentials: true, observe: 'response' }; return headers; } // #region PUBLIC METHODS public getGoogleTagManagerSettings(): Observable { return this.http.get( this.googleTagManagerSettingsUrl, this.getRequestHeaders() ); } public init(gtmAuthKey, gtmContainerKey, gtmPreviewKey) { window.dataLayer = window.dataLayer || []; window.dataLayer.push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' }); // tslint:disable-next-line: max-line-length const script = `https://www.googletagmanager.com/gtm.js?id=${gtmContainerKey}&>m_auth=${gtmAuthKey}>m_preview=${gtmPreviewKey}>m_cookies_win=x`; this.scriptService.loadScriptByLocation(script, true); } public trackUserAction( virtualEvent: string, virtualEventParam: string ): void { // tslint:disable-next-line: prefer-const let dataLayer = (window as any).dataLayer; if (dataLayer) { dataLayer.push({ event: this.constants.PP_TRACK_ACTION, 'virtual-event': virtualEvent, 'virtual-event-param': virtualEventParam }); } } }