0
votes

How to get router path on NavigationStart event in angular 8

    this.router.events
      .pipe(filter(event => event instanceof NavigationStart))
      .subscribe((event: NavigationStart) => {
         // how to get router path of on going navigation
      });

I could use event.url, but my application has some of the named outlet, url is mixed of opened named outlet. so looking to find router path of ongoing navigation on NavigationStart.

2

2 Answers

0
votes

Use ActivatedRoute instead of Router

You may subscribe url observable and join segments or use snapshot. It is well documented here.

https://angular.io/api/router/ActivatedRoute#properties

0
votes

Inject both the Router and ActivatedRoute services.

When the navigation starts, traverse the activated route to find the outlet.

You can use the following code as a starting point.

this.router.events
    .pipe(
        filter(event => event instanceof NavigationStart),
        map(() => this.activatedRoute),
        map(activatedRoute => {
            while (activatedRoute.firstChild !== null) {
                activatedRoute = activatedRoute.firstChild
            }

            return activatedRoute
        }),
        filter(activatedRoute => activatedRoute.outlet === "primary"),
        mergeMap(activatedRoute => activatedRoute.url),
    )

Note: This code will work even if you write it in your root component. The activated route doesn't only denote the route for a particular component that injected it. An activated route represents the entire route tree that led up to your current route.

In your root component activated route is a reference to the route that activated the component i.e. "/". However, you can travel down the route tree to visit other routes (if any).

Similarly, in other components the activated route is a reference to the route that activated that component. But you can traverse up and down to visit other routes.