2017-03-01 98 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);