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

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


当前回答

可以在.ts文件中使用

import { Route, Router, NavigationStart } from '@angular/router';

constructor(private router: Router) {}

this.router.events.subscribe(value => {
      if (value instanceof NavigationStart) {
        console.log(value) // your current route
      }
    });

其他回答

你可以使用this.activatedRoute.pathFromRoot。

import {ActivatedRoute} from "@angular/router";
constructor(public activatedRoute: ActivatedRoute){

}

在pathFromRoot的帮助下,您可以获得父URL的列表,并检查URL中所需的部分是否与您的条件匹配。

欲了解更多信息,请查看本文http://blog.2muchcoffee.com/getting-current-state-in-angular2-router/ 或者从NPM安装ng2-router-helper

npm install ng2-router-helper

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

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 8中获取当前路由器,只需这样做

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

然后在构造函数中注入它

constructor(private route: ActivatedRoute){}

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

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

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

将Location注入组件并读取Location .path(); 你需要在某个地方添加ROUTER_DIRECTIVES,这样Angular才能解析Location。你需要在这个模块中添加import: [RouterModule]。

更新

在V3 (RC.3)路由器中,您可以注入ActivatedRoute,并使用它的snapshot属性访问更多细节。

constructor(private route:ActivatedRoute) {
  console.log(route);
}

or

constructor(private router:Router) {
  router.events.subscribe(...);
}

另见Angular 2的路由器事件侦听器

这可能是你的答案,使用激活路由的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'];
        });
    }
}