[英]Angular 2 Get current route
因此,我需要以某种方式检查我是否在主页上并做某事,而在其他页面中则不这样做。 还在所有页面上导入该组件。
如果我在主页上,如何检测该组件?
谢谢
试试这个,
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.
}
}
试试吧
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
}
});
}
}
从本机窗口对象中尝试其中任何一个。
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);
注意:请勿在服务器端部渲染中使用它
您可以使用Angular Location Service。
import { Location } from '@angular/common';
您可以使用以下方式访问路径:
location.path();
如果您需要完整的URL,请按如下方式使用LOCATION实例: -
([Location][1])location.href = https://test-mydomain.com/#/securelogin?name=batman
如果您想要相对URL,请使用ROUTER实例,如下: -
this.router.url = securelogin?name=batman
根据角度4遵循以下完整代码段: -
constructor( private router: Router) {
console.log(this.router.url);
/**
* securelogin?name=batman
*/
console.log(location.href);
/**
* https://test-mydomain.com/#/securelogin?name=batman
*/
}
我正准备回答这个问题,但我对BigBrother也有同样的答案。 这个答案适用于那些在URL上使用“#”的人,因为它只在某些路由器位置代码上返回“/”。
这是我的一个项目的示例代码:
this.router.events.subscribe((event) => {
if(event instanceof NavigationEnd) {
this.currentPage = event.url;
if ( event.url != '/admin') {
setTimeout(()=>{
this.modalRef = this.modalService.show(ModalSurveyComponent,this.config);
}, 3000);
}
}
});
因此弹出窗口仅显示当前路线是否为“/ admin”
import { RouterStateSnapshot } from '@angular/router';
constructor(private state: RouterStateSnapshot) {
console.log("Current Url Path", state);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.