目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
当前回答
this.router.events.subscribe((val) => {
const currentPage = this.router.url; // Current page route
const currentLocation = (this.platformLocation as any).location.href; // Current page url
});
其他回答
import { Router, NavigationEnd } from "@angular/router";
constructor(private router: Router) {
// Detect current route
router.events.subscribe(val => {
if (val instanceof NavigationEnd) {
console.log(val.url);
}
});
}
新建路由器>= RC.3
最好和一个简单的方法来做到这一点是!
import { Router } from '@angular/router';
constructor(router: Router) {
router.events.subscribe((url:any) => console.log(url));
console.log(router.url); // to print only path eg:"/login"
}
对我来说,在AuthGuardService实现CanActivate访问当前路由时,接受的答案不工作,因为路由还没有完全处理。我在这里回答了同样的问题(https://stackoverflow.com/a/68541653/1479486),但如果你只是想从这里复制粘贴,这是我的解决方案:
const finalUrl = this.router.getCurrentNavigation()?.finalUrl;
const isLoginPage = finalUrl?.root.children['primary'].segments[0]?.path === 'login';
将Location注入组件并读取Location .path(); 你需要在某个地方添加ROUTER_DIRECTIVES,这样Angular才能解析Location。你需要在这个模块中添加import: [RouterModule]。
更新
在V3 (RC.3)路由器中,您可以注入ActivatedRoute,并使用它的snapshot属性访问更多细节。
constructor(private route:ActivatedRoute) {
console.log(route);
}
or
constructor(private router:Router) {
router.events.subscribe(...);
}
另见Angular 2的路由器事件侦听器
可以在.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
}
});