4
votes

How can I get the static route path of the current router-outlet component, what was activated by angular in router events?

I need it in app.component, because it would be redundant if I have to do in all component with activatedRoute.snapshot

self.router.events.subscribe(event => {
    if (event instanceof NavigationEnd) {
        //I need here the path of route E.G '/page/:id/' from root

    }
});

Update: In routing:

export const MAIN_ROUTES: Routes = [
    { path: '', component: HomePage },
    { path: 'something', component: SomethingComponent },
    { path: 'page/:id', component: PageComponent }, //if the url is 'example.com/page/someId' than, I want to get the "path" field of this object and if I change the page, I need that inside the router event above. 
]
2

2 Answers

0
votes

ActivationEnd event has snapshot: ActivatedRouteSnapshot property. You can find the path in event.snapshot.config.path property.

Based on your router setup you might have multiple ActivationEnd events during one navigation though, usually the first one is the one in which you are interested.

Angular ActivationEnd event docs

0
votes

I think I found a hacky solution for his:

    let path = '';

    self.router.events.subscribe((event) => {
        console.log(event);

        if(event instanceof ActivationEnd) {
            if(event.snapshot) {
                if(event.snapshot.routeConfig && event.snapshot.routeConfig.path) {
                    path = path == '' ? event.snapshot.routeConfig.path : [event.snapshot.routeConfig.path, path].join('/');
                }
            }
        }

        if (event instanceof NavigationEnd) {
            //save the path, and clear it.

            self.path = path;
            path = '';
        }
    });