Angular:子路由未正确更新

标签 angular routes url-routing

我有一个带有按钮的 UserComponent (路由 user/:userId)。 单击该按钮时,路由会更改为 user/123/hobby/456,从而触发 HobbyComponent。该组件有一个带有“下一个”和“上一个”按钮的分页。单击其中一个按钮时,我需要执行以下操作:

  1. 将路由更改为新的 hobbyId(从 user/123/hobby/456 更改为 user/123/hobby/789)
  2. 更新 HobbyComponent 上的数据以显示请求的爱好

当单击 UserComponent 上的按钮时,路线可以正常工作并且 HobbyComponent 也可以毫无问题地显示。我在更新子路线时遇到问题。 如果我将 this.route.navigate 函数添加到 HobbyComponent 中来更新子路由,则路由会错误地更改:它不会替换路由中的 hobbyId,而是附加一个新的 -> user/123/hobby/< strong>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", hobbyId], {
      relativeTo: this.route.parent
    });
  }

关于Angular:子路由未正确更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65926732/

相关文章:

Angular 5 测试 : Expected to be running in 'ProxyZone' , 但未找到

angular - 没有 ComponentLoaderFactory 的提供者

typescript - 桶装进口似乎打破了装载顺序

java - Camel 为存在且公开的方法抛出 MethodNotFound

ruby-on-rails - Rails 路线 : Wrong singular for resources

ruby-on-rails - 将 get 参数添加到辅助方法

ASP.NET MVC 5 URL 取决于选择

url-routing - 如何防止用户导航离开?

javascript - 包括 Rails 中特定 View 的外部 JS

angular - 在 Angular 服务中使用 HTTP Client 时为什么要对 Observable 进行类型转换