回答
試試這個,
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.
}
}
感謝我做到這一點:d –
但此總是顯示'/'作爲URL ...即它不顯示當前頁面,只有網站的根目錄 –
對我來說正確工作。當我在HomeComponent中時它顯示/ home。 – anonym
import { RouterStateSnapshot } from '@angular/router';
constructor(private state: RouterStateSnapshot) {
console.log("Current Url Path", state);
}
雖然此代碼段可能回答此問題,但某些解釋肯定會改進它。 –
在4.4.4中,[RouterStateSnapshot](https://github.com/angular/angular/blob/4.4.4/packages/router/src/router_state.ts#L314-L350)不是注射式服務。 –
試試吧
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
}
});
}
}
//你的代碼將會在這裏 if(event.url ==='/'){this.showComponent = false;其他{ this.showComponent = true; } –
嘗試任何這些從本機窗口對象。
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);
- 1. Angular 2獲得當前防護路線
- 2. Laravel 5.1 - 獲取當前路線
- 3. 路線獲取當前路線{佔位符}值symfony
- 4. 角2獲取路線PARAMS
- 5. Angular 2和Resolve路線
- 6. Java獲取當前路徑
- 7. 使用Angular(2)routerLinkActive指令獲取彎曲的路線
- 8. Angular 2如何訪問當前路徑路徑
- 9. Angular 2:檢查路由名稱是否爲當前路徑
- 10. angular 2材料paginator獲取當前頁面索引
- 11. 如何獲取Angular 2中當前元素的引用?
- 12. Angular 2獲取地圖的當前縮放級別
- 13. 如何獲得Symfony 2中的當前路線?
- 14. Angular-Fullstack獲取當前用戶
- 15. 在Angular中獲取當前網址
- 16. 角2當前路線要在鏈接在,微博和Facebook
- 17. 塔架 - 如何獲取當前控制器和動作(當前路線)?
- 18. 如何獲得canActive路線中的當前路線?
- 19. 如何在自定義路線中獲取當前用戶?
- 20. Ember.js:從當前活動路線獲取ID
- 21. 如何在HtmlHelper中獲取當前路線?
- 22. Angular 2根據當前路由器狀態更改sidenav內容
- 23. Angular 2,無法匹配任何路線
- 24. 如何模擬Angular 2路線?
- 25. Angular 2 - 後退路線不起作用
- 26. 獲取當前圖像的路徑 - jQuery
- 27. 獲取Aurelia中的當前路由
- 28. 如何獲取當前html的路徑?
- 29. 在ApplicationRoute中獲取當前路徑
- 30. 獲取當前XmlReader位置的'路徑'
的可能的複製[如何獲得當前路徑(http://stackoverflow.com/questions/34597835/how-to-get-current-route) – Adam