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

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


当前回答

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

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

其他回答

在Angular 14中,如果你这样做

this.router.url

它总是会返回'/'

您可以使用Location服务(https://angular.io/api/common/Location)及其方法“path”来获得URL,而不是使用Router(在导航生命周期中可能还没有最终路由)。这是一个比“window.location”更好的选择。pathname,”它不会感知Angular,并且会在路径中包含基本的href。

import { Location } from '@angular/common';

constructor(private location: Location) { }

ngOnInit(): void {
    console.log(this.location.path());  // returns path

}

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

Angular 2 rc2

router.urlTree.contains(router.createUrlTree(['/home']))

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

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

角RC4:

你可以从@angular/ Router中导入Router

然后注入:

constructor(private router: Router ) {

}

然后调用它的URL参数:

console.log(this.router.url); //  /routename