2017-03-01 30 views
8

私はホームページにいるかどうかをチェックして何かを行い、他のページでそれをしないでください。また、そのコンポーネントはすべてのページにインポートされました。角2現在のルートを取得

私がホームページにいる場合、そのコンポーネントでどのように検出できますか?

おかげ

+1

可能な複製[現在のルートを取得する方法](http://stackoverflow.com/questions/34597835/how-to-get-current-route) – Adam

答えて

22

は、ネイティブウィンドウオブジェクトからこれらのいずれかを試してみてください

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

おかげで、私はそれを行う: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

、これを試してみてください。

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); 
+0

//ここにコードがあります if(event.url === '/'){ this.showComponent = false; } else { this.showComponent = true; } –

0

それを試してみてください

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. 
    } 

} 
関連する問題