2016-07-15 46 views

回答

14

您可以使用激活的路由组件的快照来获取此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

+5

我得到“TypeError:无法读取最后一个'console.log'语句的未定义属性'路径' –

+0

'snapshot.url'不从根返回状态。我有这个解决方案'this.route.snapshot.pathFromRoot.map(o => o.url [0])。join('/')' – NinjaOnSafari

4

答案user5049376给了我没有工作回答。 url属性未定义。

console.log(activatedRoute.snapshot.url[0].path); 

而不是我使用firstChild属性。

console.log(this.activatedRoute.snapshot.firstChild.url[0].path); 
+1

我也可以确认'activatedRoute.snapshot.url [0] .path '抛出'TypeError:无法读取未定义的属性'路径'。为我工作的解决方案是'activatedRoute.snapshot.firstChild.url [0] .path'。我正在使用Angular 4.0.0和Angular CLI 1.1.0。 – kimbaudi

6

这对我有用。

导入这样的:

import { Router } from '@angular/router'; 

然后将它传递给构造函数:

path: any; 

constructor(private router: Router) { 
    this.path = this.router.url; 
    console.log(this.path); 
} 
+1

如果路径中包含查询字符串,所以它不仅仅是路径。 –

5
如果你刷新页面

,你无法通过路由器或ActivatedRoute获取路线路径。 你可以使用window.location.pathname而不是那个。

+1

你救我一天:) – Ismaestro

0

我试图使用其他响应,他们都结束了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被发现。