Code Monkey home page Code Monkey logo

Comments (8)

mzuccaroli avatar mzuccaroli commented on June 21, 2024

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

from angular-google-tag-manager.

cristianrc avatar cristianrc commented on June 21, 2024

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

from angular-google-tag-manager.

cristianrc avatar cristianrc commented on June 21, 2024

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

from angular-google-tag-manager.

mzuccaroli avatar mzuccaroli commented on June 21, 2024

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?

from angular-google-tag-manager.

cristianrc avatar cristianrc commented on June 21, 2024

@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);
      }
    }
  }

from angular-google-tag-manager.

cristianrc avatar cristianrc commented on June 21, 2024

@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());
    }
  }

from angular-google-tag-manager.

mzuccaroli avatar mzuccaroli commented on June 21, 2024

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

from angular-google-tag-manager.

cristianrc avatar cristianrc commented on June 21, 2024

¿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?

from angular-google-tag-manager.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.