首页 > 解决方案 > 获取相对于父路由的 url 段

问题描述

在具有嵌套路由配置的 Angular 11 应用程序中,我想知道 url 相对于父路由是什么。

例如,如果我的路线配置是

{
'car/:id', children: [{ path: 'tyres', CarTyreComponent }],
}

并且用户在car/5/tyres,答案是"tyres"

此外,我希望能够更新和访问模板中的值,以便像这样突出显示轮胎部分:

[ngClass]="if this.router.url.startsWith('tyres') ? 'active' : ''"

但是上面的示例在嵌套时不再有效,而且我似乎陷入了 and 的可订阅和不可订阅ActivatedRoute选项Router

什么有效,但似乎是一种容易出错的方法,是这样的:

[ngClass]="this.router.url.split('/')[3] === 'tyres' ? 'active' : ''"

还有更好的方法吗?

标签: angular

解决方案


如果您尝试从子组件中获取 url 段,则它应该是:
在您的component.ts

urlToCheck$$: Subject<string> = new Subject();

constructor(private _route: ActivatedRoute){
  this._route.parent?.url.subscribe( url => this.urlToCheck$$.next(url[0].path) )`

在 html 中:

[ngClass]="(urlToCheck$$ | async) === 'tyres' ? 'active' : ''"

推荐阅读