目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
当前回答
如果你需要访问当前url,通常你必须等待NavigationEnd或NavigationStart来做一些事情。如果你只是订阅路由器事件,订阅会在路由生命周期中输出许多事件。相反,使用RxJS操作符只过滤你需要的事件。这样做的有利副作用是现在我们有更严格的类型!
constructor(private router: Router) {
router.events.pipe(
filter(ev => (ev instanceof NavigationEnd))
).subscribe((ev: NavigationEnd) => {
console.log(ev.url);
});
}
其他回答
import { Router } from '@angular/router';
constructor(router: Router) {
console.log(router.routerState.snapshot.url);
}
新的V3路由器有一个url属性。
this.router.url === '/login'
在组件文件中:
import {ActivatedRouteSnapshot} from '@angular/router';
constructor(state: ActivatedRouteSnapshot) {
console.log(state.path)
}
在路由文件中:
可以在.ts文件中使用
import { Route, Router, NavigationStart } from '@angular/router';
constructor(private router: Router) {}
this.router.events.subscribe(value => {
if (value instanceof NavigationStart) {
console.log(value) // your current route
}
});
this.router.events.subscribe((val) => {
const currentPage = this.router.url; // Current page route
const currentLocation = (this.platformLocation as any).location.href; // Current page url
});