DEV Community

Manuel Heidrich
Manuel Heidrich

Posted on • Originally published at Medium

Analytics in Ionic 3: Easily Track Page Views with a Custom Decorator

This post was originally posted on Medium.

If you develop a production Ionic app chances are you also want to integrate some kind of analytics to analyse how your app is being used. There are a lot of different options available like Google Analytics, Firebase or Flurry Analytics, but all they have in common: you have to implement to implement the tracking of your individual views.

I am usually using @ionic-native/google-analytics in my apps and since I did not really want to add this.googleAnalytics.trackView(‘SomePage’) manually to every page I tried different approaches to implement automatic view tracking. What I ended up using is a custom decorator I just need to add to any page I want to track.

How does this decorator look like?

Glad you asked. Like this:

To use it you have to modify your core module as well. If you don’t have a core module you can just do the same in your app.module.ts. (Don’t forget to change line 3 in page-track.decorator.ts in that case!)

Core module example:

And now you just have to import and add the PageTrack() decorator to your page component:

That’s it!

So how does this work?

What the page track decorator basically does is publish a ‘view:enter’ event every time a view is being entered which also passes the page name (the name of the page component to be exact).
I am using the ionViewDidEnter life cycle event of Ionic to achieve that, but you could also use other events depending on when you want the event to be published.

So all I have to do is listen to the ‘view:enter’ event in an analytics service for example and do the actual view tracking there:

I think this is a pretty neat way to add page tracking to an Ionic app. What do you think?

Top comments (1)

Collapse
 
d3vtoolsmith profile image
Petr Filipchyk

this is a great approach!
thank you