假设我有这个路由配置

exp或t const EmployeeRoutes = [
   { path: 'sales', component: SalesComponent },
   { path: 'contacts', component: ContactsComponent }
];

并通过这个URL导航到SalesComponent

/department/7/employees/45/sales

现在我想转到contacts,但由于我没有绝对路由的所有参数(例如,上例中的部门ID,7),我更喜欢使用相对链接,例如.

[routerLink]="['../contacts']"

this.router.navigate('../contacts')

which unf或tunately doesn't w或k. There may be an obvious solution but I'm not seeing it. Can anyone help out here please?

推荐答案

如果您使用的是新路由(3.0.0-beta2),则可以使用ActivatedRoute导航到相对路径,如下所示:

constructor(private router: Router, private r:ActivatedRoute) {} 

///
// DOES NOT WORK SEE UPDATE
goToContact() {
  this.router.navigate(["../contacts"], { relativeTo: this.r });
}

更新日期:2019年2月8日Angular 7.1.0

current route: /department/7/employees/45/sales

the old version will do: /department/7/employees/45/sales/contacts

根据@KCarnaille的 comments ,上述内容不适用于最新的路由.新的方法是把.parent加到this.r

    // Working(08/02/2019) 
    // DOES NOT WORK SEE UPDATE
    goToContact() {
       this.router.navigate(["../contacts"], { relativeTo: this.r.parent });
    }

the update will do: /department/7/employees/45/contacts

Update 12/12/2021 Angular > 10

正如@ziz194提到的那样,它现在是这样工作的.

constructor(private router: Router, private r:ActivatedRoute) {} 

goToContact() {
  this.router.navigate(["contacts"], { relativeTo: this.r });
}

Angular相关问答推荐

Angular Signal只指一种类型,但这里用作值.ts(2693)''

无法执行客户端功能Angular 17与ssr'

Angular 17@在大小写时切换多个值

如何用ANGLE指令覆盖Html元素的数据绑定属性

图像未显示在视图屏幕上-Angular 投影

如何使用带有17角的Swiper 11.0.5元素

react 形式之间的循环关系

使用 primeng Apollo 主题进行实时部署时多次加载 theme.css 和 preloading.css 文件

使用forkJoin和mergeMap的正确方式是什么?

Angular 15 Ref 错误:初始化前无法访问组件 A

Angular ngSubmit 不起作用(内部按钮和导入模块)

在 kubernetes 上创建 Ingress 服务以将 springboot [后端] 连接到前端 [angular]

Angular14:支持旧版浏览器的官方方式是什么?

如何在 Angular 中将tailwind 类传递给 fontawesome

错误:formControlName 必须与父 formGroup 指令一起使用.您需要添加一个 formGroup 指令

为什么Angular 12 'ng serve' 构建应用程序的速度很慢?

Angular 4 Bootstrap 下拉菜单需要 Popper.js

CustomPipe 没有提供者

Angular2动态改变CSS属性

declarations和entryComponents组件有什么区别