@@ -4,16 +4,39 @@ import { OnlineStatusService } from './online-status.service';
4
4
5
5
declare function gtag ( ...args : any ) : void ;
6
6
7
- // Using a type rather than interface because I intend to turn in into a union type later for each type of event that
8
- // can be reported.
9
- // eslint-disable-next-line @typescript-eslint/consistent-type-definitions
10
- type EventParams = {
11
- page_path : string ;
12
- } ;
7
+ interface CommandParams { }
8
+
9
+ enum GoogleCommands {
10
+ Config = 'config' ,
11
+ Event = 'event' ,
12
+ JavaScript = 'js'
13
+ }
14
+
15
+ interface ConfigParams extends CommandParams {
16
+ send_page_view ?: boolean ;
17
+ }
18
+
19
+ interface PageViewParams extends CommandParams {
20
+ page_location ?: string ;
21
+ page_title ?: string ;
22
+ }
13
23
14
24
@Injectable ( { providedIn : 'root' } )
15
25
export class AnalyticsService {
16
- constructor ( private readonly onlineStatus : OnlineStatusService ) { }
26
+ private initiated ?: Promise < void > ;
27
+ constructor ( private readonly onlineStatus : OnlineStatusService ) {
28
+ if ( typeof environment . googleTagId !== 'string' ) {
29
+ return ;
30
+ }
31
+
32
+ this . initiated = new Promise ( resolve => {
33
+ this . onlineStatus . online . then ( ( ) => {
34
+ this . send ( GoogleCommands . JavaScript , new Date ( ) ) ;
35
+ this . send ( GoogleCommands . Config , environment . googleTagId , { send_page_view : false } as ConfigParams ) ;
36
+ resolve ( ) ;
37
+ } ) ;
38
+ } ) ;
39
+ }
17
40
18
41
/**
19
42
* Logs the page navigation event to the analytics service. This method is responsible for sanitizing the URL before
@@ -22,13 +45,11 @@ export class AnalyticsService {
22
45
*/
23
46
logNavigation ( url : string ) : void {
24
47
const sanitizedUrl = sanitizeUrl ( url ) ;
25
- this . logEvent ( 'page_view' , { page_path : sanitizedUrl } ) ;
48
+ this . send ( GoogleCommands . Event , 'page_view' , { page_location : sanitizedUrl } as PageViewParams ) ;
26
49
}
27
50
28
- private logEvent ( eventName : string , eventParams : EventParams ) : void {
29
- if ( this . onlineStatus . isOnline && typeof environment . googleTagId === 'string' ) {
30
- gtag ( eventName , environment . googleTagId , eventParams ) ;
31
- }
51
+ private send ( command : GoogleCommands , name : any , params ?: CommandParams ) : void {
52
+ Promise . all ( [ this . initiated , this . onlineStatus . online ] ) . then ( ( ) => gtag ( command , name , params ) ) ;
32
53
}
33
54
}
34
55
0 commit comments