获得唯一路径使用路由器(this.router.url
)我得到字符串/list?type=abc
,有时/list
...角2:如何从完整的URL字符串
我只能从完整的网址,以获取路径/list
?
非常感谢!
获得唯一路径使用路由器(this.router.url
)我得到字符串/list?type=abc
,有时/list
...角2:如何从完整的URL字符串
我只能从完整的网址,以获取路径/list
?
非常感谢!
您可以使用激活的路由组件的快照来获取此URL。
import { Router, ActivatedRoute } from '@angular/router';
constructor(
private router: Router,
private activatedRoute: ActivatedRoute) {
console.log("routes");
console.log(activatedRoute.snapshot.url); // array of states
console.log(activatedRoute.snapshot.url[0].path);
}
链接到原来那么由何塞摹Varanam How to get current route
答案user5049376给了我没有工作回答。 url属性未定义。
console.log(activatedRoute.snapshot.url[0].path);
而不是我使用firstChild属性。
console.log(this.activatedRoute.snapshot.firstChild.url[0].path);
我也可以确认'activatedRoute.snapshot.url [0] .path '抛出'TypeError:无法读取未定义的属性'路径'。为我工作的解决方案是'activatedRoute.snapshot.firstChild.url [0] .path'。我正在使用Angular 4.0.0和Angular CLI 1.1.0。 – kimbaudi
这对我有用。
导入这样的:
import { Router } from '@angular/router';
然后将它传递给构造函数:
path: any;
constructor(private router: Router) {
this.path = this.router.url;
console.log(this.path);
}
如果路径中包含查询字符串,所以它不仅仅是路径。 –
我试图使用其他响应,他们都结束了undefined。
所以我这样做:
#AppComponent
constructor(private router: Router){
// Subscribe to RouterEvents
this.router.events
.subscribe((event) => {
if (event instanceof NavigationStart) {
// Could add more chars url:path?=;other possible
const urlDelimitators = new RegExp(/[?//,;&:#$+=]/);
let currentUrlPath = event.url.slice(1).split(urlDelimitators)[0];
console.log('URL_PATH: ', currentUrlPath);
}
});
}
我订阅到路由器的变化,所以当NavitionStartEvent发生新URL_PATH被发现。
我得到“TypeError:无法读取最后一个'console.log'语句的未定义属性'路径' –
'snapshot.url'不从根返回状态。我有这个解决方案'this.route.snapshot.pathFromRoot.map(o => o.url [0])。join('/')' – NinjaOnSafari