Reputation: 29
I'm trying to connect an Angular 10 application to the analytics for the page views.
This is as far as I can get:
this.router.events.subscribe((event: any) => {
if (event instanceof NavigationEnd) {
this.analyticsService.sendPageView(event.urlAfterRedirects);
}
});
The problem is that I get item views and not page views. For example, for the route /item/:id
it will generate a different url for each item's id
:
But this is essentially one page (a page to display a specific item) and shouldn't generate different path for the analytics.
I must get something like /item/:id
without the parsed parameters.
Or maybe if I could retrieve the current component name?
Upvotes: 2
Views: 596
Reputation: 5736
It's possible to listen to the router events and get the path from the route snapshots. The component name is also accessible from the event.snapshot.component
property but it's very likely that it will be minified in the production build.
const activationEnd$ = this.router.events.pipe(filter<ActivationEnd>(event => event instanceof ActivationEnd));
const navigationEnd$ = this.router.events.pipe(filter<NavigationEnd>(event => event instanceof NavigationEnd));
activationEnd$
.pipe(
map(event => event.snapshot.routeConfig.path),
buffer(navigationEnd$),
map(paths => paths.reverse().join('/')),
distinctUntilChanged()
)
.subscribe(path => this.analyticsService.sendPageView(path));
Upvotes: 1