目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
当前回答
我也有同样的问题
this.router.url
我用查询参数获取当前路由。我做的一个变通方法是使用这个:
this.router.url.split('?')[0]
这不是一个很好的解决方案,但很有帮助。
其他回答
将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的路由器事件侦听器
对我来说,在AuthGuardService实现CanActivate访问当前路由时,接受的答案不工作,因为路由还没有完全处理。我在这里回答了同样的问题(https://stackoverflow.com/a/68541653/1479486),但如果你只是想从这里复制粘贴,这是我的解决方案:
const finalUrl = this.router.getCurrentNavigation()?.finalUrl;
const isLoginPage = finalUrl?.root.children['primary'].segments[0]?.path === 'login';
当我想要根据路线改变背景时,我面临着这个问题。但它只在我浏览网站时工作,而不是当我刷新页面时。
在router.events.subscribe()中,这是事件。导航时的Url,刷新时的this。router。Url。
现在它起作用了:
import { ActivatedRoute, Router, NavigationStart } from '@angular/router';
constructor(private router: Router) {}
public ngOnInit() {
this.router.events.subscribe((events:any) => {
let theme = '';
if (events instanceof NavigationStart) { theme = events.url; }
else { theme = this.router.url; }
if(theme === '/videos') { ... }
}
在Angular 14中,如果你这样做
this.router.url
它总是会返回'/'
您可以使用Location服务(https://angular.io/api/common/Location)及其方法“path”来获得URL,而不是使用Router(在导航生命周期中可能还没有最终路由)。这是一个比“window.location”更好的选择。pathname,”它不会感知Angular,并且会在路径中包含基本的href。
import { Location } from '@angular/common';
constructor(private location: Location) { }
ngOnInit(): void {
console.log(this.location.path()); // returns path
}
import { Router } from '@angular/router';
constructor(router: Router) {
console.log(router.routerState.snapshot.url);
}