Angular 2获取当前路线

Ara*_*yan 15 routes typescript angular2-routing angular

因此,我需要以某种方式检查我是否在主页上并做某事,而在其他页面中则不这样做.还在所有页面上导入该组件.

如果我在主页上,如何检测该组件?

谢谢

Viv*_*ngh 39

试试这个,

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.
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 除了这总是显示`/`作为URL ...即它不显示当前页面,只显示网站的根目录 (11认同)
  • @RaulA这就是我遇到的问题.您知道从应用程序组件获取非根当前路由的方法吗? (7认同)
  • 我认为这里有一些混淆与使用此代码的位置有关.如果你在托管`<router-outlet>`标签的`app.component`中使用它,它将始终返回`/`而在子组件中它正常工作. (4认同)
  • 根据[Angular Style Guide](https://angular.io/guide/styleguide):不要使用_underscore标记私有变量 (2认同)

Pan*_*pam 33

试试吧

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
      }
    });
  }
}
Run Code Online (Sandbox Code Playgroud)


San*_*rde 5

从本机窗口对象尝试其中任何一个。

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);
Run Code Online (Sandbox Code Playgroud)

注意:不要在服务器端渲染中使用它