Adding in Analytics
Explore how to integrate an analytics service that tracks route changes in Angular applications. Understand using RxJS to listen for navigation events and log page views effectively, enabling better monitoring of user navigation patterns.
We'll cover the following...
Routing analytics
Let’s hook up some analytics trackers to Angular’s router. Instead of listening in on individual routes, this service needs to know about every route change. Generate a new service and attach it to the routing module with ng g service analytics.
⚠️ While working locally, make sure you’re on the latest version of the Angular CLI. Older versions will fail, with
"Error: Specified module does not exist."
Open the fresh analytics.service.ts and modify it to add in some structure for recording routing changes:
Components analytics
This service just logs any route change to the console. You can import any analytics tool to connect the external tool with Angular. The real excitement goes on in app.component.ts:
-
Line 4:
AppComponentnow requires injecting both the Router and the newly createdAnalyticsService. Don’t forget toimportthese. -
Line 7: As covered before,
router.eventsis an observable that emits on any event the router might care to send off. -
Line 9: The analytics code only cares about recording page loads, so we filter out any emitted event that isn’t an instance of
NavigationEnd. -
Line 12: Finally, inform the analytics code that there’s been a new page change.
There are other events to listen in for, but this serves as a simple example for capturing events on the router.
import { AppPage } from './app.po';
describe('rx-photos App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should display welcome message', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('Welcome to app!');
});
});
Analytics log in console
📝 Please note that the Console in the above illustration is a feature of the Chrome browser, that can be used by opening the application in the new tab and using the Inspect feature of the Chrome browser.