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

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


当前回答

方法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;

其他回答

在Angular2 Rc1中,你可以注入一个routessegment,然后将它传递给.navigate()方法:

constructor(private router:Router,private segment:RouteSegment) {}

ngOnInit() {
  this.router.navigate(["explore"],this.segment)
}

在组件文件中:

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

constructor(state: ActivatedRouteSnapshot) {
    console.log(state.path)
}

在路由文件中:

router.events。订阅(e => { if (e instanceof NavigationEnd) { 这一点。currentUrl = e.url; } });

this.router.events.subscribe((val) => {
   const currentPage = this.router.url; // Current page route
  const currentLocation = (this.platformLocation as any).location.href; // Current page url
});
import {ActivatedRoute} from '@angular/router';
constructor(private route:ActivatedRoute){
    console.log(this.route.routeConfig.path);
}