Search code examples
angulargoogle-analyticsrxjsgoogle-tag-managergoogle-analytics-4

angular Google Analytics gtag config fires only at the first page


In an Angular app, I have an event router subscription to track page changes but the "collect" network call is only fired on the first time the gtag is triggered.

in my Index.html:

  <!-- Google tag (gtag.js) -->
  <script async src="https://www.googletagmanager.com/gtag/js?id=TRACKING-ID"></script>
  <script>
    window.dataLayer = window.dataLayer || [];
    function gtag() { dataLayer.push(arguments); }
    gtag('js', new Date());
  </script>

and in the my service.ts:

  public trackGaPageViews(): void {
    if (this.cloudConfiguration.configuration?.googleAnalyticsEnabled) {
      this.router.events
      .pipe(takeUntil(this.cleanupStream))
      .subscribe(event => {
        if (event instanceof NavigationEnd) {
          gtag('config', this.googleAnalyticsId, {
            'page_path': event.urlAfterRedirects
          });
        }
      });
    }
  }

I can see the events pushed into the DataLayer:

enter image description here

But there's only one page_view event in the network section:

enter image description here

I don't understand why i dont see more network calls (hence i dont see the event in the analytics dashboard), the gtag is fired on every page change.

Does anyone have an idea?


Solution

  • You may be looking for page_view event, config only need to be run once.

      public trackGaPageViews(): void {
        if (this.cloudConfiguration.configuration?.googleAnalyticsEnabled) {
          this.router.events
          .pipe(takeUntil(this.cleanupStream))
          .subscribe(event => {
            if (event instanceof NavigationEnd) {
              gtag('event', 'page_view', {
                'page_path': event.urlAfterRedirects
              });
            }
          });
        }
      }
    

    You may need to move the config code to the root component's ngOnInit

    ...
    export class AppComponent {
    
        ngOnInit(): void {
            gtag('config', this.googleAnalyticsId, {
                'page_path': event.urlAfterRedirects
            });
        }
        ...