目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
当前回答
在Angular2 Rc1中,你可以注入一个routessegment,然后将它传递给.navigate()方法:
constructor(private router:Router,private segment:RouteSegment) {}
ngOnInit() {
this.router.navigate(["explore"],this.segment)
}
其他回答
我也有同样的问题
this.router.url
我用查询参数获取当前路由。我做的一个变通方法是使用这个:
this.router.url.split('?')[0]
这不是一个很好的解决方案,但很有帮助。
角RC4:
你可以从@angular/ Router中导入Router
然后注入:
constructor(private router: Router ) {
}
然后调用它的URL参数:
console.log(this.router.url); // /routename
到目前为止,我的路径如下-
this.router.url.subscribe(value => {
// you may print value to see the actual object
// console.log(JSON.stringify(value));
this.isPreview = value[0].path === 'preview';
})
其中,路由器是ActivatedRoute的一个实例
在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
}
这适用于与authguard一起使用的情况
this.router.events.subscribe(event => {
if(event instanceof NavigationStart){
console.log('this is what your looking for ', event.url);
}
}
);