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

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


当前回答

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

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

其他回答

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

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

您可以使用ActivatedRoute来获取当前路由器

原文答案(RC版)

我在AngularJS谷歌Group上找到了一个解决方案,非常简单!

ngOnInit() {
  this.router.subscribe((url) => console.log(url));
}

这是最初的答案

https://groups.google.com/d/msg/angular/wn1h0JPrF48/zl1sHJxbCQAJ

这个是在Angular 11上测试的

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

到目前为止,我的路径如下-

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的一个实例

对我来说,在AuthGuardService实现CanActivate访问当前路由时,接受的答案不工作,因为路由还没有完全处理。我在这里回答了同样的问题(https://stackoverflow.com/a/68541653/1479486),但如果你只是想从这里复制粘贴,这是我的解决方案:

const finalUrl = this.router.getCurrentNavigation()?.finalUrl;   
const isLoginPage = finalUrl?.root.children['primary'].segments[0]?.path === 'login';