如何在NavigationEnd事件中获取当前路线配置?

时间:2018-09-28 18:23:03

标签: angular

如何获取当前路由器出口组件的静态路由路径,路由器事件中由angular激活了什么?

我需要在app.component中使用它,因为如果我必须在所有带有ActivateRoute.snapshot的组件中使用它,那将是多余的

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

    }
});

更新: 在路由中:

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. 
]

3 个答案:

答案 0 :(得分:1)

snapshot: ActivatedRouteSnapshot事件具有event.snapshot.config.path属性。您可以在ActivationEnd属性中找到路径。

根据您的路由器设置,一次导航可能会发生多个{{1}}事件,通常第一个是您感兴趣的事件。

use the History API directly

答案 1 :(得分:0)

您可以使用window.location

const location = window.location;
console.log(location);

答案 2 :(得分:0)

我认为我为他找到了一个骇人听闻的解决方案:

    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 = '';
        }
    });