After following a tutorial on implementing Google AdSense in my Angular App, I successfully integrated it. Here's what I did:
In the index.html file:
<!-- Global site tag (gtag.js) - Google Analytics -->
<script>
(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', 'UA-1223823-NOT-MY-ACTUALLY-ID', 'auto'); // Remember to replace this with your UA-ID
</script>
In my app.component.ts file:
import {Component} from '@angular/core';
import {NavigationEnd, Router} from '@angular/router';
// Declare ga as a function for setting and sending events
declare let ga: Function;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'news-bootstrap';
constructor(public router: Router) {
// Subscribe to router events and send page views to Google Analytics
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
ga('set', 'page', event.urlAfterRedirects);
ga('send', 'pageview');
}
});
}
}
TsLint gives a warning about 'declare let ga: Function':
TSLint: Don't use 'Function' as a type. Avoid using the `Function` type. Prefer a specific function type, like `() => void`.(ban-types)
I'm considering using interfaces to address this issue. Is creating an interface with methods like setPage(urlAfterRedirects: string) and sendPageView() linked to the ga attribute through the index.html script the correct approach? What is the best way to avoid using the Function
type in this scenario?
EDIT1: Can I also move the ga('create', 'UA-1223823-NOT-MY-ACTUALLY-ID', 'auto'); function to the interface?