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() { => {
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');
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

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


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();
st_date = datePipe.transform(new Date(startDate), 'yyyy-MM-dd');
end_date = datePipe.transform(new Date(endDate), 'yyyy-MM-dd');
var dataChart1 = new{
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
chart: {
'container': 'chart-1-container',
'type': 'LINE',
'options': {
'width': '100%'
var dataChart2 = new{
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',
chart: {
'container': 'chart-2-container',
'type': 'TABLE',
'options': {
'width': '100%'
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


//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);


getGAContent(params:any, headers: any){
let queryParams = new HttpParams();
for(let key in params) {
queryParams = queryParams.set(key, params[key]);
return this.http.get(``,{
params: queryParams,
headers: {
'Authorization': `Bearer ${headers.gaToken}`
map( (res: any) =>

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