如何在Angular中获取当前路线段(不是完整的url)

How to get the current route segment (not the full url) in Angular

我在 Angular 中看到很多关于获取当前路线的问题。据我所知,我审查过的每一个问题和相关答案都将 return 完整当前 URL.

constructor(router: Router){}

myMethod(){
    this.router.url // returns the full URL, regardless of where in the routing tree
                    // the component is being instantiated.
}

我想找到路由器路由到我的组件的特定网段。该组件可能在路由中被实例化多次。我当前的代码正在获取 full URL,但我想知道实例化组件的 特定段

更多信息:

该组件是自定义标签条。它提供了一个未命名的 <router-outlet>,在用户单击选项卡时在其中呈现单个选项卡内容。使用标签条的组件是延迟加载的。但是,其中一个选项卡的内容也使用相同的 Tab Strip 组件(该组件也是延迟加载的)。这就是事情崩溃的地方。在导航到其中一个嵌套选项卡时刷新浏览器时,出现错误:“无法激活已激活的插座”。

调查该错误消息,它似乎是 open issue 和 Angular。

建议的解决方案在 related issue 中删除错误,同时删除顶级 Tab Strip 的内容。我在想,如果我能更好地过滤建议的解决方案的 RouterOutlet.deactivate() 调用,我可能会消除错误,同时仍然在所有嵌套级别显示 Tab Strips 的内容。

改进后的过滤要求 Tab Strip 组件知道路由器为其实例化的当前网段。

不过,这道题是关于从Router获取当前segment的;修复导致我来到这里的错误也会有所帮助。

UrlSegment 可用于该目的。文档中的示例:

@Component({templateUrl:'template.html'})
class MyComponent {
  constructor(router: Router) {
    const tree: UrlTree = router.parseUrl('/team;id=33');
    const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET];
    const s: UrlSegment[] = g.segments;
    s[0].path; // returns 'team'
    s[0].parameters; // returns {id: 33}
  }
}

https://angular.io/api/router/UrlSegment

使用NavigationEnd。每次导航发生时,都会触发Router.events并检查是否成功仅获取当前路线。

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

event给你url属性当前路线