我们正在实施Google Analytics(分析)。我们想检索网址,参数和组件以在GA中对其进行标记。
this.router.events
.pipe(
filter(event => event instanceof NavigationEnd)
)
.subscribe((event: NavigationEnd) => {
event.urlAfterRedirects;
});
例如,导航到/ tab / brands / 12 / details / 55
/tab/brands/:BrandId/details/:productId
我们可以找到url,但找不到组件名称,也找不到参数。有什么主意吗?
您仅使用路由器事件来标识导航何时结束。一旦有了它,就不再需要router事件。相反,您需要查询激活的路由。由此,您可以获取组件和所需的任何参数。
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;
}