简体   繁体   中英

How to send Page View Event to Google Tag Manager in Angular

Until now, I was using Google Analytics directly and I was firing Page View Event manually with JavaScript from app.component.ts , like this:

constructor(private router: Router) {
  const navEndEvents = this.router.events.pipe(
    filter((event) => event instanceof NavigationEnd)
  );
  navEndEvents.subscribe((event: NavigationEnd) => {
    gtag('config', 'xxx', {
    page_path: event.urlAfterRedirects,
    page_title: event.urlAfterRedirects
    });
  })
}

Now, I want to use Google Analytics through Google Tag Manager, and not directly. How should I send Page View Event now?

I was able to do it with angular-google-tag-manager package. Once you install and configure package, you can send whatever event to GTM really easy. Refactor for Page View Event in app.component.ts looks like this:

import { GoogleTagManagerService } from 'angular-google-tag-manager';

constructor(private router: Router, private gtmService: GoogleTagManagerService) {
  const navEndEvents = this.router.events.pipe(
    filter((event) => event instanceof NavigationEnd)
  );
  navEndEvents.subscribe((event: NavigationEnd) => {
    this.gtmService.pushTag({
      event: 'pageview',
      data: {
        page_name: event.urlAfterRedirects
      }
    });
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM