We are implementing google analytics. We would like to retrieve url, params and components to tag them in GA.
this.router.events
.pipe(
filter(event => event instanceof NavigationEnd)
)
.subscribe((event: NavigationEnd) => {
event.urlAfterRedirects;
});
For example navigation to /tab/brands/12/details/55
/tab/brands/:BrandId/details/:productId
We could find the url, but not component name neither params. Any idea?
You only use the router events to identify when navigation has ended. Once you have that, you no longer need the router event. Instead, you need to query the activated route. From that you can get the component and any params you wish.
component.ts
constructor(private router: Router,
private route: ActivatedRoute
) {
}
ngOnInit(): void {
this.router.events.pipe(
// identify navigation end
filter((event) => event instanceof NavigationEnd),
// now query the activated route
map(() => this.rootRoute(this.route)),
filter((route: ActivatedRoute) => route.outlet === 'primary'),
).subscribe((route: ActivatedRoute) => {
console.log(route.snapshot.paramMap.get('id'));
console.log(route.component);
});
}
private rootRoute(route: ActivatedRoute): ActivatedRoute {
while (route.firstChild) {
route = route.firstChild;
}
return route;
}
DEMO: https://stackblitz.com/edit/router-template-svttzv
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With