Skip to main content
The AnalyticsService provides a clean interface for logging analytics events to Google Analytics 4 (GA4) with built-in environment-based enablement.

Import

import { AnalyticsService } from '@jet/services/analytics/analytics.service';
import { AnalyticsEvent } from '@jet/interfaces/analytics-event.interface';

Usage

Basic Event Tracking

import { inject } from '@angular/core';
import { AnalyticsService } from '@jet/services/analytics/analytics.service';

export class MyComponent {
  readonly #analyticsService = inject(AnalyticsService);

  trackButtonClick() {
    this.#analyticsService.logAnalyticsEvent({
      name: 'button_click',
      data: {
        button_id: 'submit',
        page: 'profile'
      }
    });
  }
}

Page View Tracking

ngOnInit() {
  this.#analyticsService.logAnalyticsEvent({
    name: 'page_view',
    data: {
      page_title: 'User Dashboard',
      page_path: '/dashboard'
    }
  });
}

Custom Events with Rich Data

onPurchase(item: Product, quantity: number) {
  this.#analyticsService.logAnalyticsEvent({
    name: 'purchase',
    data: {
      item_id: item.id,
      item_name: item.name,
      quantity: quantity,
      price: item.price,
      currency: 'USD'
    }
  });
}

Events Without Additional Data

this.#analyticsService.logAnalyticsEvent({
  name: 'user_signup'
});

Methods

logAnalyticsEvent

Logs an analytics event to Google Analytics 4.
analyticsEvent
AnalyticsEvent
required
The analytics event object containing the event name and optional data
analyticsEvent.name
string
required
The name of the event to track (e.g., ‘button_click’, ‘page_view’)
analyticsEvent.data
Record<string, boolean | null | number | string | undefined>
Optional key-value pairs with additional event parameters
return
void
This method does not return a value. Events are sent asynchronously to GA4.
Source: /home/daytona/workspace/source/src/app/services/analytics/analytics.service.ts:22
public logAnalyticsEvent(analyticsEvent: AnalyticsEvent): void {
  if (!this.#isAnalyticsEnabled) {
    return;
  }

  gtag('event', analyticsEvent.name, analyticsEvent.data as Gtag.CustomParams);
}
Example:
// Simple event
this.analyticsService.logAnalyticsEvent({
  name: 'login'
});

// Event with data
this.analyticsService.logAnalyticsEvent({
  name: 'search',
  data: {
    search_term: 'angular services',
    results_count: 42
  }
});

// User interaction
this.analyticsService.logAnalyticsEvent({
  name: 'video_play',
  data: {
    video_id: 'abc123',
    video_title: 'Getting Started',
    timestamp: Date.now()
  }
});

Configuration

Environment Setup

Configure analytics in your environment files:
// src/environments/environment.ts
export const environment = {
  isAnalyticsEnabled: false, // Disabled in development
  googleAnalyticsMeasurementId: 'G-XXXXXXXXXX'
};

// src/environments/environment.prod.ts
export const environment = {
  isAnalyticsEnabled: true, // Enabled in production
  googleAnalyticsMeasurementId: 'G-XXXXXXXXXX'
};

Injection Tokens

The service uses these injection tokens:
import { IS_ANALYTICS_ENABLED } from '@jet/injection-tokens/is-analytics-enabled.injection-token';
import { GOOGLE_ANALYTICS_MEASUREMENT_ID } from '@jet/injection-tokens/google-analytics-measurement-id.injection-token';

Provider Setup

import { ApplicationConfig } from '@angular/core';
import { IS_ANALYTICS_ENABLED } from '@jet/injection-tokens/is-analytics-enabled.injection-token';
import { GOOGLE_ANALYTICS_MEASUREMENT_ID } from '@jet/injection-tokens/google-analytics-measurement-id.injection-token';
import { environment } from './environments/environment';

export const appConfig: ApplicationConfig = {
  providers: [
    { provide: IS_ANALYTICS_ENABLED, useValue: environment.isAnalyticsEnabled },
    { provide: GOOGLE_ANALYTICS_MEASUREMENT_ID, useValue: environment.googleAnalyticsMeasurementId }
  ]
};

Type Definitions

AnalyticsEvent Interface

export interface AnalyticsEvent {
  data?: Record<string, boolean | null | number | string | undefined>;
  name: string;
}
Source: /home/daytona/workspace/source/src/app/interfaces/analytics-event.interface.ts:1

Features

Environment-Based Enablement

Analytics are automatically disabled when IS_ANALYTICS_ENABLED is false:
public logAnalyticsEvent(analyticsEvent: AnalyticsEvent): void {
  if (!this.#isAnalyticsEnabled) {
    return; // No-op in development
  }
  // ... send to GA4
}

Type Safety

The AnalyticsEvent interface ensures type-safe event data:
  • Event names must be strings
  • Event data supports: boolean, null, number, string, undefined
  • No arbitrary objects to maintain GA4 compatibility

Google Analytics 4 Integration

Uses the ga-gtag library for GA4 integration:
import { gtag, install } from 'ga-gtag';

// Installed during service construction
install(this.#googleAnalyticsMeasurementId);

// Used for event tracking
gtag('event', analyticsEvent.name, analyticsEvent.data);

Best Practices

  1. Use consistent event names - Follow GA4’s recommended event naming conventions (snake_case)
  2. Include relevant data - Add contextual information that helps analyze user behavior
  3. Avoid PII - Never include personally identifiable information in event data
  4. Keep data types simple - Stick to primitives (strings, numbers, booleans) for GA4 compatibility
  5. Test in development - Use browser dev tools to verify events when enabled

Common Patterns

export class NavigationTracker implements OnInit {
  readonly #router = inject(Router);
  readonly #analyticsService = inject(AnalyticsService);

  ngOnInit() {
    this.#router.events.subscribe(event => {
      if (event instanceof NavigationEnd) {
        this.#analyticsService.logAnalyticsEvent({
          name: 'page_view',
          data: {
            page_path: event.urlAfterRedirects,
            page_title: document.title
          }
        });
      }
    });
  }
}

Form Interaction Tracking

onFormSubmit() {
  this.#analyticsService.logAnalyticsEvent({
    name: 'form_submit',
    data: {
      form_id: 'contact',
      form_name: 'Contact Form'
    }
  });
}

onFormError(field: string) {
  this.#analyticsService.logAnalyticsEvent({
    name: 'form_error',
    data: {
      form_id: 'contact',
      field_name: field,
      error_type: 'validation'
    }
  });
}

E-commerce Tracking

trackAddToCart(product: Product) {
  this.#analyticsService.logAnalyticsEvent({
    name: 'add_to_cart',
    data: {
      item_id: product.id,
      item_name: product.name,
      item_category: product.category,
      price: product.price,
      quantity: 1
    }
  });
}

Dependencies

The AnalyticsService depends on:
  • ga-gtag - Google Analytics 4 library
  • LoggerService - For service initialization logging
  • IS_ANALYTICS_ENABLED - Environment-based feature flag
  • GOOGLE_ANALYTICS_MEASUREMENT_ID - GA4 measurement ID

Build docs developers (and LLMs) love