I am using Angular4 and trying to get analytics installed. I followed this guide:
https://blog.thecodecampus.de/angular-2-include-google-analytics-event-tracking/
But when I try to build my project, I get the error:
error TS2304: Cannot find name 'ga'.
I have checked my package.json and I have "@types/google.analytics": "0.0.38",
installed in my devDependencies.
When I start typing I can see that intellisense knows it's a UniversalAnalytics.ga
type, but I cannot get it to work.
I tried changing my code to this:
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
let ga: Function;
ga('set', 'page', event.urlAfterRedirects);
ga('send', 'pageview');
}
});
It compiles, but in the console.log I get an error stating:
Uncaught (in promise): TypeError: ga is not a function
If I change to this:
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
let ga: any;
ga('set', 'page', event.urlAfterRedirects);
ga('send', 'pageview');
}
});
I get the same error. Does anyone know why?
Here is the complete code:
import { Component, OnInit, AfterViewChecked, AfterViewInit } from "@angular/core";
import { ActivatedRoute, Params, Router, NavigationEnd } from "@angular/router";
import { ResultsService } from "./shared/results.service";
import { HeightService } from "./shared/height.service";
@Component({
selector: 'bzRoot',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, AfterViewChecked, AfterViewInit {
constructor(
private _activatedRoute: ActivatedRoute,
private _resultsService: ResultsService,
private _heightService: HeightService,
public router: Router) {
}
ngOnInit() {
this._activatedRoute.queryParams.subscribe((params: Params) => {
// Only update the elq if it changes (remember: changing a parameter causes the page to refresh)
var elq = params['elqid'];
if (elq) {
this._resultsService.elq = elq;
}
});
}
ngAfterViewChecked() {
this._heightService.resize();
}
ngAfterViewInit() {
//this.router.events.subscribe(event => {
// if (event instanceof NavigationEnd) {
// let ga: Function;
// ga('set', 'page', event.urlAfterRedirects);
// ga('send', 'pageview');
// }
//});
}
}
Somehow the @types/google.analytics package seams to be broken. Just add this to your code:
declare let ga: Function;
I'll update my blog post.
You can add google.analytics
to the types in your tsconfig.json
"types": [
"node",
"google.analytics",
],
..or you can remove the entire types
property from the config to have it use all in @types.
Check the part on 'types' here: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With