问题描述
我有一个带按钮的 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});
}
解决方法
我建立了一个简单的 Stackblitz 项目 here 来演示类似的场景。请注意,您可以在同一用户下从一个爱好导航到另一个同级爱好。
我的路线是:
const routes: Routes = [
{
path: "user/:userId",component: UserComponent,children: [{ path: "hobby/:hobbyId",component: HobbyComponent }]
}
];
HTML:
<button (click)="gotoHobby(1)">Go to hobby 1</button>
从用户到爱好代码的导航是:
async gotoHobby(hobbyId: number): Promise<void> {
await this.router.navigate(['hobby',hobbyId],{ relativeTo: this.route })
}
从爱好到爱好的导航:
HTML:
<button *ngIf="hobbyId === '1'" (click)="gotoHobby(2)">Go to hobby 2</button>
<button *ngIf="hobbyId === '2'" (click)="gotoHobby(1)">Go to hobby 1</button>
代码:
async gotoHobby(hobbyId: number): Promise<void> {
await this.router.navigate(["hobby",{
relativeTo: this.route.parent
});
}
,
你需要使用基于main路由的相对路由,而不是activated路由:
navigateToNextHobby(nextHobbyId) {
this.router.navigate([nextHobbyId],{relativeTo: this.route});
}
所以它是相对于用户路由的。