目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
当前回答
这很简单,在angular 2中,你只需要像这样导入Router库:
import { Router } from '@angular/router';
然后在组件或服务的构造函数中,你必须像这样实例化它:
constructor(private _router: Router) {}
然后在代码的任何部分,函数、方法、构造等等:
this._router.events
.subscribe(
(url:any) => {
let _ruta = "";
url.url.split("/").forEach(element => {
if(element!=="" && _ruta==="")
_ruta="/"+element;
});
console.log("route: "+_ruta); //<<<---- Root path
console.log("to URL:"+url.url); //<<<---- Destination URL
console.log("from URL:"+this._router.url);//<<<---- Current 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
}
});
将Location注入组件并读取Location .path(); 你需要在某个地方添加ROUTER_DIRECTIVES,这样Angular才能解析Location。你需要在这个模块中添加import: [RouterModule]。
更新
在V3 (RC.3)路由器中,您可以注入ActivatedRoute,并使用它的snapshot属性访问更多细节。
constructor(private route:ActivatedRoute) {
console.log(route);
}
or
constructor(private router:Router) {
router.events.subscribe(...);
}
另见Angular 2的路由器事件侦听器
如果你导入了路由器,那么你可以简单地使用一些东西
This.router.url === "/search"
否则执行以下操作
1)导入路由器
import { Router } from '@angular/router';
2)在构造函数中声明它的条目
constructor(private router: Router) { }
3)在你的工作中发挥它的价值
yourFunction(){
if(this.router.url === "/search"){
//some logic
}
}
@victor的回答帮助了我,这是和他一样的答案,但有一点细节,因为它可能会帮助到别人
在组件文件中:
import {ActivatedRouteSnapshot} from '@angular/router';
constructor(state: ActivatedRouteSnapshot) {
console.log(state.path)
}
在路由文件中:
我面临的问题是,当用户在应用程序中导航或访问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)
);
希望能有所帮助,祝你好运!