目前的文档只讨论了获取路由参数,而不是实际的路由段。

例如,如果我想找到当前路由的父,这是怎么可能的?


当前回答

本机窗口对象也可以正常工作

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);

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

其他回答

这可能是你的答案,使用激活路由的params方法从你想要读取的URL/路由获取参数,下面是演示片段

import {ActivatedRoute} from '@angular/router'; 
@Component({
})
export class Test{
constructor(private route: ActivatedRoute){
this.route.params.subscribe(params => {
             this.yourVariable = params['required_param_name'];
        });
    }
}

我也有同样的问题

this.router.url

我用查询参数获取当前路由。我做的一个变通方法是使用这个:

this.router.url.split('?')[0]

这不是一个很好的解决方案,但很有帮助。

在angular 2.2.1中(在一个基于angar2 -webpack-starter的项目中)是这样工作的:

export class AppComponent {
  subscription: Subscription;
  activeUrl: string;

  constructor(public appState: AppState,
              private router: Router) {
    console.log('[app] constructor AppComponent');
  }

  ngOnInit() {
    console.log('[app] ngOnInit');
    let _this = this;
    this.subscription = this.router.events.subscribe(function (s) {
      if (s instanceof NavigationEnd) {
        _this.activeUrl = s.urlAfterRedirects;
      }
    });
  }

  ngOnDestroy() {
    console.log('[app] ngOnDestroy: ');
    this.subscription.unsubscribe();
  }
}

在AppComponent的模板中,你可以使用{{activeUrl}}。

这个解决方案的灵感来自于RouterLinkActive的代码。

要在angular 8中获取当前路由器,只需这样做

import {ActivatedRoute} from '@angular/router';

然后在构造函数中注入它

constructor(private route: ActivatedRoute){}

如果你想获取当前路由,那么使用这个route.url

如果你有多个名称路由,比如/home/pages/list你想访问单个,那么你可以访问每个,比如这个route。url。value[0]。path

值[0]会给你主页,值[1]会给你页面,值[2]会给你列表

新建路由器>= RC.3

最好和一个简单的方法来做到这一点是!

import { Router } from '@angular/router';
constructor(router: Router) { 
      router.events.subscribe((url:any) => console.log(url));
      console.log(router.url);  // to print only path eg:"/login"
}