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

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


当前回答

可以在.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
      }
    });

其他回答

简单的方法

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

方法1:使用Angular: this.router.url

import { Component } from '@angular/core';

// Step 1: import the router 
import { Router } from '@angular/router';

@Component({
    template: 'The href is: {{href}}'
    /*
    Other component settings
    */
})
export class Component {
    public href: string = "";

    //Step 2: Declare the same in the constructure.
    constructor(private router: Router) {}

    ngOnInit() {
        this.href = this.router.url;
        // Do comparision here.....
        ///////////////////////////
        console.log(this.router.url);
    }
}

方法二:窗口。如果你不想使用路由器,就像我们在Javascript中做的那样

this.href= window.location.href;

如果你导入了路由器,那么你可以简单地使用一些东西

This.router.url === "/search"

否则执行以下操作

1)导入路由器

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

2)在构造函数中声明它的条目

constructor(private router: Router) { }

3)在你的工作中发挥它的价值

yourFunction(){
    if(this.router.url === "/search"){
        //some logic
    }
}

@victor的回答帮助了我,这是和他一样的答案,但有一点细节,因为它可能会帮助到别人

将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的路由器事件侦听器

要找到当前路由的父路由,你可以使用相对路由从路由器获取UrlTree:

var tree:UrlTree = router.createUrlTree(['../'], {relativeTo: route});

然后得到主出口的分段:

tree.root.children[PRIMARY_OUTLET].segments;