目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
当前回答
到目前为止,我的路径如下-
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的一个实例
其他回答
到目前为止,我的路径如下-
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的一个实例
我也有同样的问题
this.router.url
我用查询参数获取当前路由。我做的一个变通方法是使用这个:
this.router.url.split('?')[0]
这不是一个很好的解决方案,但很有帮助。
获取路由段:
import { ActivatedRoute, UrlSegment } from '@angular/router';
constructor( route: ActivatedRoute) {}
getRoutes() { const segments: UrlSegment[] = this.route.snapshot.url; }
下面是我在Angular 2.3.1中工作的地方。
location: any;
constructor(private _router: Router) {
_router.events.subscribe((data:any) => { this.location = data.url; });
console.warn(this.location); // This should print only path e.g. "/home"
}
数据是一个对象,我们需要该对象中包含的url属性。所以我们在变量中获取这个值,我们也可以在HTML页面中使用这个变量。例如,我想显示一个div仅当用户在主页上。在这种情况下,我的路由器url值将是/home。所以我可以用下面的方式写一个div:
<div *ngIf="location == '/home'">
This is content for the home page.
</div>
import { Router } from '@angular/router';
constructor(router: Router) {
console.log(router.routerState.snapshot.url);
}