目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
当前回答
要在angular 8中获取当前路由器,只需这样做
import {ActivatedRoute} from '@angular/router';
然后在构造函数中注入它
constructor(private route: ActivatedRoute){}
如果你想获取当前路由,那么使用这个route.url
如果你有多个名称路由,比如/home/pages/list你想访问单个,那么你可以访问每个,比如这个route。url。value[0]。path
值[0]会给你主页,值[1]会给你页面,值[2]会给你列表
其他回答
新的V3路由器有一个url属性。
this.router.url === '/login'
如果你不能访问路由器,这是一个更简单的方法。url(例如,如果你使用skipLocationChange),你可以使用以下:
import { Location } from '@angular/common';
constructor(private readonly location: Location) {}
ngOnInit(): void {
console.log(this.location.path());
}
在angular 2.2.1中(在一个基于angar2 -webpack-starter的项目中)是这样工作的:
export class AppComponent {
subscription: Subscription;
activeUrl: string;
constructor(public appState: AppState,
private router: Router) {
console.log('[app] constructor AppComponent');
}
ngOnInit() {
console.log('[app] ngOnInit');
let _this = this;
this.subscription = this.router.events.subscribe(function (s) {
if (s instanceof NavigationEnd) {
_this.activeUrl = s.urlAfterRedirects;
}
});
}
ngOnDestroy() {
console.log('[app] ngOnDestroy: ');
this.subscription.unsubscribe();
}
}
在AppComponent的模板中,你可以使用{{activeUrl}}。
这个解决方案的灵感来自于RouterLinkActive的代码。
如果你需要访问当前url,通常你必须等待NavigationEnd或NavigationStart来做一些事情。如果你只是订阅路由器事件,订阅会在路由生命周期中输出许多事件。相反,使用RxJS操作符只过滤你需要的事件。这样做的有利副作用是现在我们有更严格的类型!
constructor(private router: Router) {
router.events.pipe(
filter(ev => (ev instanceof NavigationEnd))
).subscribe((ev: NavigationEnd) => {
console.log(ev.url);
});
}
this.router.events.subscribe((val) => {
const currentPage = this.router.url; // Current page route
const currentLocation = (this.platformLocation as any).location.href; // Current page url
});