Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get component name and params on NavigationEnd event?

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?

like image 790
Stefdelec Avatar asked Jan 27 '20 16:01

Stefdelec


1 Answers

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

like image 56
Kurt Hamilton Avatar answered Nov 15 '22 03:11

Kurt Hamilton