import { Injectable } from '@angular/core' ; import { NavigationEnd , Router , RouterEvent } from '@angular/router' ; import { distinctUntilChanged , filter , tap } from 'rxjs/operators' ; declare let ga ; export enum EventCategory { SideNav = 'sideNav' , Outbound = 'outboundLink' , Login = 'login' , Install = 'install' } export enum EventAction { Play = 'play' , Click = 'click' } @ Injectable ( ) export class GoogleAnalyticsService { constructor ( public router ) { } public initPageViewTracking ( ) { this . router . events . pipe ( filter ( ( event ) => event instanceof NavigationEnd ) , distinctUntilChanged ( ( previous , current ) => { return previous . url === current . url ; } ) ) . subscribe ( ( event ) => { this . setPage ( event . urlAfterRedirects ) ; } ) ; } /**
     * set user after login success.
     */ public setUsername ( username ) { if ( typeof ga === 'function' ) { ga ( 'set' , 'userId' , username ) ; } } /**
     * set page after navigation success
     */ public setPage ( path ) { if ( typeof ga === 'function' ) { ga ( 'set' , 'page' , path ) ; ga ( 'send' , 'pageview' ) ; } } param eventCategory param eventAction param eventLabel param eventValue public emitEvent ( eventCategory , eventAction , eventLabel ? , eventValue ? ) { if ( typeof ga === 'function' ) { ga ( 'send' , 'event' , { eventCategory , eventAction , eventLabel , eventValue , } ) ; } } param socialNetwork param socialAction param socialTarget public emitSocial ( socialNetwork , socialAction , socialTarget ) { if ( typeof ga === 'function' ) { ga ( 'send' , 'social' , { socialNetwork , socialAction , socialTarget , } ) ; } } param timingCategory param timingVar param timingValue param timingLabel public emitTiming ( timingCategory , timingVar , timingValue , timingLabel ? ) { if ( typeof ga === 'function' ) { ga ( 'send' , 'timing' , { timingCategory , timingVar , timingValue , timingLabel , } ) ; } } public emitException ( exDescription ? , exFatal ? ) { if ( typeof ga === 'function' ) { ga ( 'send' , 'exception' , { exDescription , exFatal , } ) ; } } }