2017-09-04 53 views
2

我知道這已被問及很多次了,我已經花了超過2個小時的時間尋找解決方案。如何在Angular 2.0+中獲取當前網址

所以請不要評論爲重複或投票下來重複提問。

我現在的網址是:http://localhost:4200/configuration

下面是許多網上找到的解決辦法,我想實現的一個。

export class AppComponent implements OnInit{ 
    title = 'app'; 
    constructor(private router: Router, private activatedRoute: ActivatedRoute) { 

    } 

    ngOnInit() { 
    console.log("On Init"); 
    console.log(this.router.url); 
    console.log(this.activatedRoute.url); 
    //this.router.navigate(['/login']); 
    } 
} 

在重新載入頁面時,我會得到下面的輸出結果。

On Init 
\ 

我只是得到空的網址。 我很好奇,知道我失蹤了。

感謝您的幫助。

+0

你期望輸出什麼? –

+0

不應該得到/配置? –

+0

顯示你的路線confguratoin –

回答

2

您可以使用location.href。另一種選擇是使用DOCUMENT'@angular/platform-browser'

import { DOCUMENT } from '@angular/platform-browser'; 

constructor(@Inject(DOCUMENT) private document: any){ 
    console.log(location.pathname); 
    console.log(location.href); 
    console.log(this.document.location.href); 
} 

如果你只想從你的網址,以獲取「/configuration」,然後使用location.pathname

演示here

+0

這是Javascript的。有沒有辦法做到這一點在角? –

+1

這是有角度的。你看過演示了嗎? – Faisal

+1

它的一種黑客。我以麪糊的方式做到了,但明天在辦公室提交一次 –

0

這會給 「/配置」

import { Router, NavigationEnd } from '@angular/router'; 
import { isPlatformBrowser } from '@angular/common'; 

.... 

constructor(
    private router: Router, 
.... 

ngOnInit() { 
    if (isPlatformBrowser) { 
     this.router.events 
     .filter(event => event instanceof NavigationEnd) 
     .subscribe(() => { 
      console.log(this.router.routerState.snapshot.url); 
     }) 
    } 
    } 
0

您正確訪問屬性。但是,您在設置之前訪問它。請參閱:

https://stackblitz.com/edit/angular-8phmvc

如果您檢查瀏覽器登錄就可以看到每個組件的生命週期的一部分,有其設置。

但長話短說,而不是ngOnInit嘗試ngAfterViewChecked或尋找另一種方式來訂閱使用路由器的當前位置。