2017-03-01 100 views
8

因此,我需要以某種方式檢查我是否在主頁上並執行某些操作,而在其他頁面中則不這樣做。也是在所有頁面上導入該組件。Angular 2獲取當前路線

如何在主頁上檢測該組件?

感謝

+1

的可能的複製[如何獲得當前路徑(http://stackoverflow.com/questions/34597835/how-to-get-current-route) – Adam

回答

22

試試這個,

import { Router } from '@angular/router'; 
export class MyComponent implements OnInit { 

    constructor(private router:Router) { ... } 

    ngOnInit() { 
     let currentUrl = this.router.url; /// this will give you current url 

     // your logic to know if its my home page. 
    } 

} 
+0

感謝我做到這一點:d –

+10

但此總是顯示'/'作爲URL ...即它不顯示當前頁面,只有網站的根目錄 –

+0

對我來說正確工作。當我在HomeComponent中時它顯示/ home。 – anonym

-2
import { RouterStateSnapshot } from '@angular/router'; 

constructor(private state: RouterStateSnapshot) { 
    console.log("Current Url Path", state); 
} 
+4

雖然此代碼段可能回答此問題,但某些解釋肯定會改進它。 –

+2

在4.4.4中,[RouterStateSnapshot](https://github.com/angular/angular/blob/4.4.4/packages/router/src/router_state.ts#L314-L350)不是注射式服務。 –

17

試試吧

import { Component } from '@angular/core'; 
import { Router, NavigationEnd } from '@angular/router'; 

@Component({...}) 

export class MyComponent { 

    constructor(private router:Router) { 

    router.events.subscribe(event => { 

     if (event instanceof NavigationEnd) { 
     console.log("current url",event.url); // event.url has current url 
     // your code will goes here 
     } 
    }); 
    } 
} 
+0

//你的代碼將會在這裏 if(event.url ==='/'){this.showComponent = false;其他{ this.showComponent = true; } –

0

嘗試任何這些從本機窗口對象。

console.log('URL:' + window.location.href); 
console.log('Path:' + window.location.pathname); 
console.log('Host:' + window.location.host); 
console.log('Hostname:' + window.location.hostname); 
console.log('Origin:' + window.location.origin); 
console.log('Port:' + window.location.port); 
console.log('Search String:' + window.location.search);