【问题标题】:Angular: child route is not updated correctlyAngular:子路由未正确更新
【发布时间】:2021-05-01 17:39:01
【问题描述】:

我有一个带有按钮的 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/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


【解决方案1】:

我建立了一个简单的 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
    });
  }

【讨论】:

  • 嗨,Benny,感谢您的回复和花时间在这个问题上!我需要通过单击爱好组件内的按钮从一个爱好导航到另一个爱好。在您的情况下,路由更改是从用户组件触发的,正如我在问题中所说,这不是问题。你知道我如何改变 hobbyComponent 内部的路线吗?因为您提供的导航代码不起作用
  • 我更新了我的答案和我的项目 - 添加了从爱好到爱好的导航。请看一下
  • 我的荣幸。很高兴为您提供帮助!
【解决方案2】:

你需要使用基于main路由的相对路由,而不是activated路由:

navigateToNextHobby(nextHobbyId) {
    this.router.navigate([nextHobbyId], {relativeTo: this.route});
}

所以它是相对于 user 路线的。

【讨论】:

  • 谢谢!我不确定 this.route 应该是什么。我试图这样做:navigateToNextHobby(nextHobbyId) { this.router.navigate([nextHobbyId], {relativeTo: this.router.url});但是,我得到一个错误“类型'字符串'不可分配给类型'ActivatedRoute'”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-25
  • 2013-06-29
  • 1970-01-01
  • 2018-01-26
  • 2015-04-14
相关资源
最近更新 更多