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

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


当前回答

方法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.subscribe(value => {
    // you may print value to see the actual object
    // console.log(JSON.stringify(value));
    this.isPreview = value[0].path === 'preview';
})

其中,路由器是ActivatedRoute的一个实例

如果你需要访问当前url,通常你必须等待NavigationEnd或NavigationStart来做一些事情。如果你只是订阅路由器事件,订阅会在路由生命周期中输出许多事件。相反,使用RxJS操作符只过滤你需要的事件。这样做的有利副作用是现在我们有更严格的类型!

constructor(private router: Router) {
    router.events.pipe(
      filter(ev => (ev instanceof NavigationEnd))
    ).subscribe((ev: NavigationEnd) => {
      console.log(ev.url);
    });
}

可以在.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, NavigationEnd } from '@angular/router';

constructor(private router: Router) {
    router.events.filter(event => event instanceof NavigationEnd)
        .subscribe(event => {
            console.log(event);
        });
}

主要是。ts进口

import 'rxjs/add/operator/filter';

EDIT

现代的方式

import {filter} from 'rxjs/operators';

router.events.pipe(
    filter(event => event instanceof NavigationEnd)
)
    .subscribe(event => {
        console.log(event);
    });

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

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的回答帮助了我,这是和他一样的答案,但有一点细节,因为它可能会帮助到别人