如何获取当前路由器出口组件的静态路由路径,路由器事件中由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.
]
答案 0 :(得分:1)
snapshot: ActivatedRouteSnapshot
事件具有event.snapshot.config.path
属性。您可以在ActivationEnd
属性中找到路径。
根据您的路由器设置,一次导航可能会发生多个{{1}}事件,通常第一个是您感兴趣的事件。
答案 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 = '';
}
});