目前的文档只讨论了获取路由参数,而不是实际的路由段。

例如,如果我想找到当前路由的父,这是怎么可能的?


当前回答

我也有同样的问题

this.router.url

我用查询参数获取当前路由。我做的一个变通方法是使用这个:

this.router.url.split('?')[0]

这不是一个很好的解决方案,但很有帮助。

其他回答

对我来说,在AuthGuardService实现CanActivate访问当前路由时,接受的答案不工作,因为路由还没有完全处理。我在这里回答了同样的问题(https://stackoverflow.com/a/68541653/1479486),但如果你只是想从这里复制粘贴,这是我的解决方案:

const finalUrl = this.router.getCurrentNavigation()?.finalUrl;   
const isLoginPage = finalUrl?.root.children['primary'].segments[0]?.path === 'login'; 

新的V3路由器有一个url属性。

this.router.url === '/login'
import {ActivatedRoute} from '@angular/router';
constructor(private route:ActivatedRoute){
    console.log(this.route.routeConfig.path);
}

这可能是你的答案,使用激活路由的params方法从你想要读取的URL/路由获取参数,下面是演示片段

import {ActivatedRoute} from '@angular/router'; 
@Component({
})
export class Test{
constructor(private route: ActivatedRoute){
this.route.params.subscribe(params => {
             this.yourVariable = params['required_param_name'];
        });
    }
}
import { Router } from '@angular/router';
constructor(router: Router) { 
      console.log(router.routerState.snapshot.url);
}