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

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


当前回答

使用这个

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);
    });

其他回答

import { Router } from '@angular/router';
constructor(router: Router) { 
      console.log(router.routerState.snapshot.url);
}

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

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

当我想要根据路线改变背景时,我面临着这个问题。但它只在我浏览网站时工作,而不是当我刷新页面时。

在router.events.subscribe()中,这是事件。导航时的Url,刷新时的this。router。Url。

现在它起作用了:

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

constructor(private router: Router) {}

public ngOnInit() {
    this.router.events.subscribe((events:any) => {
        let theme = '';
        if (events instanceof NavigationStart) { theme = events.url; }
        else { theme = this.router.url; }
        
        if(theme === '/videos') { ... }
}

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

我面临的问题是,当用户在应用程序中导航或访问URL(或在特定URL上刷新)时,我需要URL路径来显示基于URL的子组件。

更重要的是,我想要一个可以在模板中使用的Observable,所以路由器。Url不是一个选项。和路由器。事件订阅,因为在组件模板初始化之前触发路由。

this.currentRouteURL$ = this.router.events.pipe(
     startWith(this.router),
     filter(
         (event) => event instanceof NavigationEnd || event instanceof Router
     ),
     map((event: NavigationEnd | Router) => event.url)
);

希望能有所帮助,祝你好运!