2017-03-03 74 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()); 
    } 
}