https://github.com/angular/angular
Raw File
Tip revision: 6353b77f891d4a74953b23afcf5dd6f64db09a09 authored by Alex Rickabaugh on 20 December 2017, 20:50:50 UTC
docs: add changelog for 5.1.2
Tip revision: 6353b77
ga.service.ts
import { Inject, Injectable } from '@angular/core';

import { environment } from '../../environments/environment';
import { WindowToken } from 'app/shared/window';

@Injectable()
/**
 * Google Analytics Service - captures app behaviors and sends them to Google Analytics (GA).
 * Presupposes that GA script has been loaded from a script on the host web page.
 * Associates data with a GA "property" from the environment (`gaId`).
 */
export class GaService {

  private previousUrl: string;

  constructor(@Inject(WindowToken) private window: Window) {
    this.ga('create', environment['gaId'] , 'auto');
  }

  locationChanged(url: string) {
    this.sendPage(url);
  }

  sendPage(url: string) {
    // Won't re-send if the url hasn't changed.
    if (url === this.previousUrl) { return; }
    this.previousUrl = url;
    this.ga('set', 'page', '/' + url);
    this.ga('send', 'pageview');
  }

  ga(...args) {
    this.window['ga'](...args);
  }
}
back to top