目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
目前的文档只讨论了获取路由参数,而不是实际的路由段。
例如,如果我想找到当前路由的父,这是怎么可能的?
当前回答
你可以使用this.activatedRoute.pathFromRoot。
import {ActivatedRoute} from "@angular/router";
constructor(public activatedRoute: ActivatedRoute){
}
在pathFromRoot的帮助下,您可以获得父URL的列表,并检查URL中所需的部分是否与您的条件匹配。
欲了解更多信息,请查看本文http://blog.2muchcoffee.com/getting-current-state-in-angular2-router/ 或者从NPM安装ng2-router-helper
npm install ng2-router-helper
其他回答
给那些还在寻找这个的人。在Angular 2上。有几种方法。
constructor(private router: Router, private activatedRoute: ActivatedRoute){
// string path from root to current route. i.e /Root/CurrentRoute
router.url
// just the fragment of the current route. i.e. CurrentRoute
activatedRoute.url.value[0].path
// same as above with urlSegment[]
activatedRoute.url.subscribe((url: urlSegment[])=> console.log(url[0].path))
// same as above
activatedRoute.snapshot.url[0].path
// the url fragment from the parent route i.e. Root
// since the parent is an ActivatedRoute object, you can get the same using
activatedRoute.parent.url.value[0].path
}
引用:
https://angular.io/docs/ts/latest/api/router/index/ActivatedRoute-interface.html https://angular.io/docs/ts/latest/api/router/index/Router-class.html https://angular.io/docs/ts/latest/guide/router.html
如果你导入了路由器,那么你可以简单地使用一些东西
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)
}
在路由文件中:
import { Router } from '@angular/router';
constructor(router: Router) {
console.log(router.routerState.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
}
});