【发布时间】:2017-07-21 03:58:08
【问题描述】:
所以我需要以某种方式检查我是否在主页上并做某事,而在其他页面上不这样做。该组件也在所有页面上导入。
如果我在主页上,如何检测该组件???
谢谢
【问题讨论】:
标签: angular typescript routes angular2-routing
所以我需要以某种方式检查我是否在主页上并做某事,而在其他页面上不这样做。该组件也在所有页面上导入。
如果我在主页上,如何检测该组件???
谢谢
【问题讨论】:
标签: angular typescript routes angular2-routing
试试这个,
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.
}
}
【讨论】:
/显示为URL...即它不显示当前页面,只显示站点的根目录
<router-outlet> 标记的app.component 中使用它,它将始终返回/,而在子组件中它可以正常工作。
试试看
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 定位服务。
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按照完整的sn-p如下:-
constructor( private router: Router) {
console.log(this.router.url);
/**
* securelogin?name=batman
*/
console.log(location.href);
/**
* https://test-mydomain.com/#/securelogin?name=batman
*/
}
【讨论】:
我正要回答这个问题,但我和老大哥的答案相同。此答案适用于那些在其 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);
}
【讨论】: