2017-03-01 2 views
8

So muss ich irgendwie überprüfen, ob ich auf der Startseite bin und etwas tun und in anderen Seiten nicht tun. Auch diese Komponente wurde auf allen Seiten importiert.Angular 2 Aktuelle Route

Wie kann ich auf dieser Komponente erkennen, wenn ich auf der Startseite bin ???

Dank

+1

Mögliche Duplikat von [Wie aktuelle Route bekommen] (http://stackoverflow.com/questions/34597835/how-to-get-current-route) – Adam

Antwort

22

Try this,

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

Dank ich das tun: D –

+10

außer dass diese zeigt immer '/' als URL ... dh es zeigt nicht die aktuelle Seite an, nur der Stamm der Seite –

+0

Funktioniert für mich korrekt. Es zeigt/home, wenn ich in HomeComponent bin. – anonym

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

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

erhalten wird. Während dieses Snippet die Frage beantworten kann, würde eine Erklärung es sicherlich verbessern. –

+2

In 4.4.4 ist [RouterStateSnapshot] (https://github.com/angular/angular/blob/4.4.4/packages/router/src/router_state.ts#L314-L350) kein injizierbarer Dienst. –

17

Probieren Sie es

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

// Ihr Code wird hier gehen if (event.url === '/') { this.showComponent = false; } sonst { this.showComponent = true; } –

0

eine dieser aus dem nativen Fensterobjekt Versuchen.

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