76634: Implement GoogleAnalyticsService

This commit is contained in:
Bruno Roemers
2021-02-01 19:10:15 +01:00
parent d21cca2875
commit d574ffafa4
8 changed files with 68 additions and 23 deletions

View File

@@ -33,6 +33,7 @@ import { models } from './core/core.module';
import { LocaleService } from './core/locale/locale.service';
import { hasValue } from './shared/empty.util';
import { KlaroService } from './shared/cookies/klaro.service';
import {GoogleAnalyticsService} from './statistics/google-analytics.service';
@Component({
selector: 'ds-app',
@@ -70,7 +71,8 @@ export class AppComponent implements OnInit, AfterViewInit {
private menuService: MenuService,
private windowService: HostWindowService,
private localeService: LocaleService,
@Optional() private cookiesService: KlaroService
@Optional() private cookiesService: KlaroService,
@Optional() private googleAnalyticsService: GoogleAnalyticsService,
) {
/* Use models object so all decorators are actually called */
@@ -84,7 +86,10 @@ export class AppComponent implements OnInit, AfterViewInit {
// set the current language code
this.localeService.setCurrentLanguageCode();
angulartics2GoogleAnalytics.startTracking();
// analytics
if (hasValue(googleAnalyticsService)) {
googleAnalyticsService.addTrackingIdToPage();
}
angulartics2DSpace.startTracking();
metadata.listenForRouteChange();

View File

@@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { GoogleAnalyticsService } from './google-analytics.service';
describe('GoogleAnalyticsService', () => {
let service: GoogleAnalyticsService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(GoogleAnalyticsService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@@ -0,0 +1,40 @@
import { Injectable } from '@angular/core';
import {Angulartics2GoogleAnalytics} from 'angulartics2/ga';
import {ConfigurationDataService} from '../core/data/configuration-data.service';
import {getFirstCompletedRemoteData} from '../core/shared/operators';
import {isEmpty, isNotEmpty} from '../shared/empty.util';
@Injectable()
export class GoogleAnalyticsService {
constructor(
private angulartics: Angulartics2GoogleAnalytics,
private configService: ConfigurationDataService,
) { }
addTrackingIdToPage() {
this.configService.findByPropertyName('google.analytics.key').pipe(
getFirstCompletedRemoteData(),
).subscribe((remoteData) => {
// make sure we got a success response from the backend
if (!remoteData.hasSucceeded) { return; }
const trackingId = remoteData.payload.values[0];
// make sure we received a tracking id
if (isEmpty(trackingId)) { return; }
// add trackingId snippet to page
const keyScript = document.createElement('script');
keyScript.innerHTML = `(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
'ga('create', '${trackingId}', 'auto');`;
document.body.appendChild(keyScript);
// start tracking
this.angulartics.startTracking();
});
}
}

View File

@@ -23,7 +23,6 @@ export interface GlobalConfig extends Config {
notifications: INotificationBoardOptions;
submission: SubmissionConfig;
universal: UniversalConfig;
gaTrackingId: string;
logDirectory: string;
debug: boolean;
defaultLanguage: string;

View File

@@ -132,8 +132,6 @@ export const environment: GlobalConfig = {
async: true,
time: false
},
// Google Analytics tracking id
gaTrackingId: '',
// Log directory
logDirectory: '.',
// NOTE: will log all redux actions and transfers in console

View File

@@ -110,8 +110,6 @@ export const environment: Partial<GlobalConfig> = {
async: true,
time: false
},
// Google Analytics tracking id
gaTrackingId: '',
// Log directory
logDirectory: '.',
// NOTE: will log all redux actions and transfers in console

View File

@@ -25,25 +25,9 @@ export function main() {
}
});
addGoogleAnalytics();
return platformBrowserDynamic().bootstrapModule(BrowserAppModule, {preserveWhitespaces:true});
}
function addGoogleAnalytics() {
// Add google analytics if key is present in config
const trackingId = environment.gaTrackingId;
if (isNotEmpty(trackingId)) {
const keyScript = document.createElement('script');
keyScript.innerHTML = `(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');`
+ 'ga(\'create\', \'' + environment.gaTrackingId + '\', \'auto\');';
document.body.appendChild(keyScript);
}
}
// support async tag or hmr
if (hasValue(environment.universal) && environment.universal.preboot === false) {
bootloader(main);

View File

@@ -30,6 +30,7 @@ import {
LocationToken
} from '../../app/core/services/browser-hard-redirect.service';
import { LocaleService } from '../../app/core/locale/locale.service';
import {GoogleAnalyticsService} from '../../app/statistics/google-analytics.service';
export const REQ_KEY = makeStateKey<string>('req');
@@ -99,6 +100,10 @@ export function getRequest(transferState: TransferState): any {
provide: HardRedirectService,
useClass: BrowserHardRedirectService,
},
{
provide: GoogleAnalyticsService,
useClass: GoogleAnalyticsService,
},
{
provide: LocationToken,
useFactory: locationProvider,