如何在 NavigationEnd 事件中获取组件名称和参数?
How to get component name and params on NavigationEnd event?
我们正在实施 google 分析。我们想检索 url、参数和组件以在 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,但找不到组件名称和参数。有什么想法吗?
您仅使用路由器事件来识别导航何时结束。一旦你有了它,你就不再需要路由器事件了。相反,您需要查询激活的路由。从那里你可以得到你想要的组件和任何参数。
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;
}
我们正在实施 google 分析。我们想检索 url、参数和组件以在 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,但找不到组件名称和参数。有什么想法吗?
您仅使用路由器事件来识别导航何时结束。一旦你有了它,你就不再需要路由器事件了。相反,您需要查询激活的路由。从那里你可以得到你想要的组件和任何参数。
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;
}