2017-03-03 32 views
3

当我使用console.log(_router.url)时,无法获取网址。它只返回/(斜杠)Angular 2 - 无法从路由器获取网址

当我做下面的代码:

constructor(
    private el: ElementRef, 
    private _auth:AuthenticationService, 
    @Inject(AppStore) private store: Store<AppState>, 
    private _router:Router, 
) { 

    console.log(_router); 
    console.log(_router.url); 
    } 

这是console.log(_router) enter image description here

时(...),结果被点击它显示"/languages"

enter image description here

但是当我console.log(_router.url)这只是它打印

enter image description here

+0

你得到这个解决。答案似乎不适合我。 – Hiran

回答

2

你总是可以尝试从位置服务中获得的路线

constructor(location: Location) { 
    console.log(location.path()); 
} 

Location docs

1

@Owain面包车布拉克尔的答案是正确的,但缺少一些细节,我无法使用this.router.url(正如StackOverflow中的其他答案中所建议的),所以我使用了location.path(),结果类似。

这是我的代码:

// This is important because when you use Location in the constructor it 
// gets accepted but the wrong library is used. 
import { Location } from '@angular/common'; 

export class MainComponent { 
    constructor(public location: Location) { 
     console.log(this.location.path()); 
    } 
}