Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Multiple installations of Google Tag Manager detected #55

Closed
cristianrc opened this issue Feb 11, 2021 · 8 comments
Closed

Multiple installations of Google Tag Manager detected #55

cristianrc opened this issue Feb 11, 2021 · 8 comments

Comments

@cristianrc
Copy link

cristianrc commented Feb 11, 2021

my configuration:

in app.module.ts:

import { GoogleTagManagerModule } from 'angular-google-tag-manager';
imports: [
    ...
    GoogleTagManagerModule.forRoot({
      id: environment.gtm.id,
      gtm_auth: environment.gtm.gtm_auth,
      gtm_preview: environment.gtm.gtm_preview,
    })
]

in app.component.ts:

constructor(
        ...
        private gtmService: GoogleTagManagerService,
    ) { }
 this.router.events.forEach(item => {
            if (item instanceof NavigationEnd) {
                const gtmTag = {
                    event: 'atm.pageview',
                    pageHost: 'hostname',
                    pagePath: item.url,
                    pageTitle: 'title',
                };
                this.gtmService.pushTag(gtmTag);
            }
        });

Result:

image

in html:
image

my app:
Angular version: 10.2.4
Angular material: 10.2.7
angular-google-tag-manager: 1.3.0

-I have tried as import and as provider
-I tried only with id

I have the same error

@mzuccaroli
Copy link
Owner

Hi Cristian,
in your foreach you need to use the pushOnDataLayer function not the pushTag

the pushOnDataLayer function add a new event on the existing datalayer
the pushTag litterally add a new tag to the dom and triggers the multiple instances

@cristianrc
Copy link
Author

Hola Cristian,
en tu foreach necesitas usar la función pushOnDataLayer , no pushTag

la función pushOnDataLayer agrega un nuevo evento en la capa de datos existente
la pushTag agrega literalmente una nueva etiqueta al dom y activa las múltiples instancias

this.gtmService.pushOnDataLayer ?

this method does not exist in the service of plugin

@cristianrc
Copy link
Author

cristianrc commented Feb 12, 2021

@mzuccaroli In the documentation of the Readme file you have the same example code

@mzuccaroli
Copy link
Owner

sorry, my bad
it looks like that you have multiple service instances and the "isLoaded" param is never set true, so every event you invoke add a new tag.
Can you paste your full app.component file?

@cristianrc
Copy link
Author

cristianrc commented Feb 14, 2021

@mzuccaroli It is exactly the same code example that you have in the Readme

app.component.ts

  import { Component, isDevMode, OnInit, OnDestroy } from '@angular/core';
  import { Router, NavigationEnd } from '@angular/router';
  import { MsalService, BroadcastService } from '@azure/msal-angular';
  import { Logger, CryptoUtils } from 'msal';
  import { Subscription } from 'rxjs';
  import { AuthService } from '@shared/service/auth.service';
  import { PixelService } from '@shared/service/pixel.service';
  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss'],
  })
  export class AppComponent implements OnInit, OnDestroy {
    subscriptions: Subscription[] = [];
  
    title = 'application';
    isIframe = false;
  
    constructor(
      private authService: MsalService,
      private broadcastService: BroadcastService,
      private router: Router,
      private authTempService: AuthService,
      private pixelService: PixelService,
    ) {}
  
    ngOnInit(): void {
      let loginSuccessSubscription: Subscription;
      let loginFailureSubscription: Subscription;
      let loginssoFailureSubscription: Subscription;
  
      this.isIframe = window !== window.parent && !window.opener;
  
      loginSuccessSubscription = this.broadcastService.subscribe('msal:loginSuccess', () => {
        if (isDevMode()) {
          console.log('succsess:', this.authService.getAccount());
        }
        this.authTempService.setMessage('Se ha logeado correctamente');
        this.router.navigate([`/home`]);
      });
  
      loginFailureSubscription = this.broadcastService.subscribe('msal:loginFailure', (error) => {
        if (error.error) {
          this.authTempService.getMessageError(error.error);
        }
        if (isDevMode()) {
          console.log('login Failure ' + error);
        }
      });
  
      loginssoFailureSubscription = this.broadcastService.subscribe('msal:ssoFailure', (payload) => {
        this.authTempService.setMessage('Login falló: ' + payload);
        if (isDevMode()) {
          console.log('sso Failure ' + payload);
        }
      });
  
      this.subscriptions.push(loginSuccessSubscription);
      this.subscriptions.push(loginFailureSubscription);
      this.subscriptions.push(loginssoFailureSubscription);
  
      this.authService.handleRedirectCallback((authError, response) => {
        if (authError) {
          console.error('Redirect Error: ', authError.errorMessage);
          return;
        }
  
        console.log('Redirect Success: ', response.accessToken);
      });
  
      if (isDevMode()) {
        this.authService.setLogger(
          new Logger(
            (logLevel, message, piiEnabled) => {
              console.log('MSAL Logging: ', message);
            },
            {
              correlationId: CryptoUtils.createNewGuid(),
              piiLoggingEnabled: false,
            },
          ),
        );
      }
      this.setPixel();
    }
  
    ngOnDestroy(): void {
      this.subscriptions.forEach((subscription) => subscription.unsubscribe());
    }
  
    setPixel(): void {
      const hostName = window.location.hostname;
      this.router.events.forEach((item) => {
        if (item instanceof NavigationEnd) {
          const gtmTag = {
            event: 'atm.pageview',
            pageHost: hostName,
            pagePath: item.url,
            pageTitle: 'App',
          };
          this.pixelService.pushTag(gtmTag);
        }
      });
    }
  }

pixel.service.ts

  import { Injectable } from '@angular/core';
  import { AuthService } from '@shared/service/auth.service';
  import { GoogleTagManagerService } from 'angular-google-tag-manager';
  import Utils from '@shared/app.utils';
  
  @Injectable({
    providedIn: 'root',
  })
  export class PixelService {
    constructor(private authService: AuthService, private gtmService: GoogleTagManagerService) {}
  
    initGtm(): void {
      if (!Utils.isLocalMode()) {
        this.gtmService.addGtmToDom();
      }
    }
  
    pushTag(tag: object): void {
      if (!Utils.isLocalMode()) {
        const userId = this.authService.getUserId();
        const gtmTag = { ...tag, ...{ userId: userId } };
        console.log(
          '%c Google Tag ↴',
          'background: rgba(26,115,232,.1); color: #1565cf; font-weight: 800; font-size: 12px',
        );
        console.table(gtmTag);
        this.gtmService.pushTag(gtmTag);
      }
    }
  }

@cristianrc
Copy link
Author

@mzuccaroli I just tried this code and it doesn't work either:

"isLoaded" param is never set true again

  import { Component, OnInit, OnDestroy } from '@angular/core';
  import { Router, NavigationEnd } from '@angular/router';
  import { Subscription } from 'rxjs';
  import { GoogleTagManagerService } from 'angular-google-tag-manager';
  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss'],
  })
  export class AppComponent implements OnInit, OnDestroy {
    subscriptions: Subscription[] = [];
  
    title = 'app';
    isIframe = false;
  
    constructor(private router: Router, private googleTagManagerService: GoogleTagManagerService) {}
  
    ngOnInit(): void {
      this.router.events.forEach((item) => {
        if (item instanceof NavigationEnd) {
          const gtmTag = {
            event: 'atm.pageview',
            pageHost: 'hostName',
            pagePath: item.url,
            pageTitle: 'App',
          };
          this.googleTagManagerService.pushTag(gtmTag);
        }
      });
    }
  
    ngOnDestroy(): void {
      this.subscriptions.forEach((subscription) => subscription.unsubscribe());
    }
  }

@mzuccaroli
Copy link
Owner

have you tried to use the gtm service directly in your app.component ?
like this example: https://github.com/mzuccaroli/angular-google-tag-manager/blob/master/demo-application/src/app/app.component.ts

@cristianrc
Copy link
Author

cristianrc commented Feb 14, 2021

¿Ha intentado utilizar el servicio gtm directamente en el componente de su aplicación?
como este ejemplo: https://github.com/mzuccaroli/angular-google-tag-manager/blob/master/demo-application/src/app/app.component.ts

@mzuccaroli yes

look at my last answer: #55 (comment)

the problem will be the lazy load?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants