subscribe to router change events, and send Google Analytics a pageview event for the current url each time it changes
import { Injectable } from '@angular/core';
import { NavigationEnd, Router } from '@angular/router';
declare const ga: any;
// see: https://developers.google.com/analytics/devguides/collection/analyticsjs/single-page-applications
@Injectable()
export class AnalyticsService {
constructor(public router: Router) {
router.events.distinctUntilChanged((previous: any, current: any) => {
if (current instanceof NavigationEnd) {
return previous.url === current.url;
}
return true;
}).subscribe((x: any) => {
ga('set', 'page', x.urlAfterRedirects || x.url);
ga('send', 'pageview');
})
}
}