【发布时间】:2021-05-01 17:39:01
【问题描述】:
我有一个带有按钮的 UserComponent(路由 user/:userId)。 单击按钮时,路由更改为 user/123/hobby/456,触发 HobbyComponent。这个组件有一个带有“下一个”和“上一个”按钮的分页。单击其中一个按钮时,我需要执行以下操作:
- 将路由更改为新的 hobbyId(从 user/123/hobby/456 更改为 user/123/hobby/789)
- 更新 HobbyComponent 上的数据以显示请求的爱好
当点击 UserComponent 上的按钮时,路由正常工作,HobbyComponent 显示没有问题。我对更新子路由有疑问。 如果我将 this.route.navigate 函数添加到 HobbyComponent 以更新子路由,则路由更改不正确:它不会替换路由中的 hobbyId,而是附加一个新的 -> user/123/hobby/456/789 之后应用中断,因为这条路线不存在。 如何解决?我想避免将路由更改事件传递给 UserComponent,因为组件没有父子关系,所以我看不到传递事件的简单方法。
路线:
export const UserRoutes: Routes = [
{ path: 'user/:userId', component: UserComponent, children: [
{ path: 'hobby/:hobbyId', component: HobbyComponent},
]}
]
用户组件:
// button click event
openHobby() {
this.router.navigate([this.hobbyId], {relativeTo: this.activatedRoute});
}
爱好组件:
navigateToNextHobby(nextHobbyId) {
this.router.navigate([nextHobbyId], {relativeTo: this.activatedRoute});
}
【问题讨论】:
-
试试
this.router.navigate(['..', nextHobbyId], {relativeTo: this.activatedRoute}); -
或
this.router.navigate(['../' + nextHobbyId], {relativeTo: this.activatedRoute}); -
@Benny 我认为
..或../仅用于模板相对路由。这是由{relativeTo: this.activatedRoute}实现的。
标签: angular routes url-routing