How to send events in Google Analytics, get data from Google Analytics in Angular?

In the previous story, I wrote how to set up an analytics account so that we can track data, now what if I want to track certain data only.

So for this, there are the events connected in google analytics you can send event by wrapping some unique info, and by using the Google API or embed google API we can get the google analytics data.

app.component.ts File

declare interface Window {
ga: Function;
}

declare var ga: any[];
export class AppComponent {ngAfterViewInit() {
this.router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
//sending pageviews for every route change (<any>window).ga('set', 'page', event.urlAfterRedirects);
(<any>window).ga('send', 'pageview');
//But we are sending events only for some specific pagesif(specifyCondition){
console.log('parent analytics send event');
(<any>window).ga('send','event', event.urlAfterRedirects, 'unique username', 'web');
}else{
console.log('other user so not sending event')
}
}
});
}
}}
Google Analytics Events

When you send the event, the realtime events can be seen under the realtime -> events section.

(<any>window).ga('send','event', event.urlAfterRedirects, 'unique username', 'web');

Here in the Event Category, I send event.urlAfterRedirects, Event Action I send ‘unique username’, and for Event Label, I send ‘web’.

So after sending google events, now we need to fetch the google analytics data so for that we need to use to google APIs

Check this for more details https://ga-dev-tools.appspot.com/embed-api/server-side-authorization/

GO to Google Console and set up your project and then go to Apis and Services as following

Google Console Dashboard

Make sure you enable the google analytics api

Google Analytics Api

Now if its already on click on manage and then click on Create Credentials and go to Service Account and create the service account for the project.

Now add that service account to google analytics as a user.

Go to Google Analytics -> Admin -> Account User Management

Then add the user and now you can get the data from google API. As we all know we need some token to hit an API there is an OAuth but for that, we need to go through the process of the refresh token

Use the Google API library and add the service account there and then you can generate the access token, so for doing please do it on the server-side, not on the client-side.

Now on the client-side just use the embed code or you directly call API too.

Save the View Id in the environment file, then the fetch from there so we can maintain multiple environments(staging, development, production)

As mention in the google documents we need the script, so we are adding in the HTML file

index.html FIle

<script>
(function(w,d,s,g,js,fs){
g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(f){this.q.push(f);}};
js=d.createElement(s);fs=d.getElementsByTagName(s)[0];
js.src='https://apis.google.com/js/platform.js';
fs.parentNode.insertBefore(js,fs);js.onload=function(){g.load('analytics');};
}(window,document,'script'));
</script>

my-component.ts file

First fetch the token from the serverside then call the ready functiongetGaData(){let st_date: string, end_date: string;
let endDate = new Date(), startDate = new Date();
startDate.setDate(endDate.getDate()-30);
st_date = datePipe.transform(new Date(startDate), 'yyyy-MM-dd');
end_date = datePipe.transform(new Date(endDate), 'yyyy-MM-dd');
var dataChart1 = new gapi.analytics.googleCharts.DataChart({
query: {
'ids': this.gaIds, // <-- Replace with the ids value for your view.
'start-date': st_date,//YYYY-MM-DD format,
'end-date': end_date,//YYYY-MM-DD format,
'metrics': 'ga:totalEvents',
'dimensions': 'ga:date',//date ,ga:eventLabel
'filters':'ga:eventAction=='+this.uniueparam
},
chart: {
'container': 'chart-1-container',
'type': 'LINE',
'options': {
'width': '100%'
}
}
});
dataChart1.execute();
var dataChart2 = new gapi.analytics.googleCharts.DataChart({
query: {
'ids': this.gaIds, // <-- Replace with the ids value for your view.
'start-date': st_date,
'end-date': end_date,
'metrics': 'ga:totalEvents',
'dimensions': 'ga:eventCategory,ga:date',
'filters':'ga:eventAction=='+this.uniueparam
},
chart: {
'container': 'chart-2-container',
'type': 'TABLE',
'options': {
'width': '100%'
}
}
});
dataChart2.execute();
this.loading = false;
})
}

mycomponent.html file

<div id="chart-1-container"></div> <--here line chart rendered -->
<div id="chart-2-container"></div><--here table rendered -->

Also if we don’t need that or I want to build a custom chart or table we hit the API too.

Create a google-service file and inject it into the module, import in the ts, and then assign the alias name

my-component.ts

getGAData(){
//gaServ is an alias of google service class
this.gaServ.getGAContent(gaData, {gaToken: this.gaToken})
.subscribe((data: any) => {
console.log(data, 'data using google api');
//set data in any form
}, err => {
console.log('err using google api', err);
this.tokenErr();
});
}

google-service.ts

getGAContent(params:any, headers: any){
let queryParams = new HttpParams();
for(let key in params) {
queryParams = queryParams.set(key, params[key]);
}
return this.http.get(`https://content.googleapis.com/analytics/v3/data/ga`,{
params: queryParams,
headers: {
'Authorization': `Bearer ${headers.gaToken}`
}
}
).pipe(
map( (res: any) =>
res
)
);
}

Also internally the embedded API doing the same, they also hit the API and then using Google Chart, rendered the Data

Happy Google Analytics, Track events Anything using Google.

Happy Coding 😊

B.E Software Developer, Enthusiastic, Ego-surfing