目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
当前回答
获取路由段:
import { ActivatedRoute, UrlSegment } from '@angular/router';
constructor( route: ActivatedRoute) {}
getRoutes() { const segments: UrlSegment[] = this.route.snapshot.url; }
其他回答
可以在.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
}
});
新建路由器>= 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"
}
我也有同样的问题
this.router.url
我用查询参数获取当前路由。我做的一个变通方法是使用这个:
this.router.url.split('?')[0]
这不是一个很好的解决方案,但很有帮助。
我面临的问题是,当用户在应用程序中导航或访问URL(或在特定URL上刷新)时,我需要URL路径来显示基于URL的子组件。
更重要的是,我想要一个可以在模板中使用的Observable,所以路由器。Url不是一个选项。和路由器。事件订阅,因为在组件模板初始化之前触发路由。
this.currentRouteURL$ = this.router.events.pipe(
startWith(this.router),
filter(
(event) => event instanceof NavigationEnd || event instanceof Router
),
map((event: NavigationEnd | Router) => event.url)
);
希望能有所帮助,祝你好运!
简单的方法
import { Router } from '@angular/router';
constructor(router: Router) {
router.events.subscribe((url:any) => console.log(url));
console.log(router.url); <---------- to get only path eg:"/signUp"
}