【问题标题】:Add query params to current child route from parent route component in Angular从Angular中的父路由组件向当前子路由添加查询参数
【发布时间】:2019-11-15 07:13:20
【问题描述】:

我有这样的路由配置:

[
  {
    path: 'parent',
    component: ParentComponent,
    children: [
      {
        path: 'child-one',
        component: ChildOneComponent
      },
      {
        path: 'child-two',
        component: ChildTwoComponent
      }
    ]
  }
]

ParentComponent 内,我有一个按钮,当单击该按钮时,应将查询参数添加到当前路由/URL。我找到了建议此解决方案的其他答案:

// inside ParentComponent
constructor(
  private router: Router,
  private route: ActivatedRoute
) { }

onButtonClick() {
  this.router.navigate([], {
    relativeTo: this.route,
    queryParams: { myparam: true },
    queryParamsHandling: 'merge',
  })
}

但是,在ParentComponent 中使用此解决方案会导致导航相对于父路由,而不是子路由。因此,例如,如果用户位于 URL /parent/child-one 并单击按钮,浏览器将导航到 /parent?myparam=true 而不是 /parent/child-one?myparam=true

由于此代码在我的应用程序的顶部组件中运行,我宁愿不进行遍历 ActivatedRoute 对象寻找传递给 relativeTo 参数的适当路径的麻烦事,因为有一个可能会出现很多边缘情况。

Router 对象确实在其url 属性中提供了完整的当前 URL,但是,像这样使用该 URL 不会触发导航事件:

onButtonClick() {
  this.router.navigate([this.router.url], {
    queryParams: { myparam: true },
    queryParamsHandling: 'merge',
  })
}

this.router.navigateByUrl 尝试同样的事情也不会触发导航事件:

onButtonClick() {
  this.router.navigateByUrl(this.router.url, {
    queryParams: { myparam: true },
    queryParamsHandling: 'merge',
  })
}

replaceUrl: true 添加到NavigationExtras 对象(navigateByUrl 的第二个参数)也不会导致导航事件。

【问题讨论】:

  • 你可以尝试改用this.router.navigateByUrl
  • 使用当前 URL 调用 this.router.navigateByUrl 也不会触发导航事件。
  • 你添加了 { replaceUrl: true } 参数吗?
  • 是的,我尝试使用和不使用 replaceUrl 参数。
  • 对我来说这种方式是可行的`this.router.navigate([], { queryParams: { myparam: true }, relativeTo: this.activatedRoute, fragment: this.activatedRoute.snapshot.fragment, queryParamsHandling :'合并', });` .并且不管哪个组件调用它

标签: angular angular-router


【解决方案1】:

好的,经过大量实验,我想出了这个解决方案:

onButtonClick() {
  const urlTree = this.router.parseUrl(this.router.url)
  urlTree.queryParams['myparam'] = 'true'
  this.router.navigateByUrl(urlTree)
}

在处理一个简化示例时,我无法重现该问题,因此我显然在我的项目中遇到了一个边缘情况,我无法完全追踪。

在挖掘navigateByUrl的源代码后,似乎将当前URL和新URL进行了比较,如果确定它们相同,则跳过导航事件。但是,在此比较中似乎没有考虑 NavigationExtras 参数,如果您要更改查询字符串参数,这显然很重要。上面概述的解决方案消除了这个缺陷,因为查询参数被集成到navigateByUrl 的第一个参数中,这是用于确定新 URL 是否与旧 URL 匹配的参数。 (见源码here。)

【讨论】:

    【解决方案2】:

    在'app-routing.module.ts'文件中,添加如下代码:

    @NgModule({ 进口:[RouterModule.forRoot(路线,{ paramsInheritanceStrategy: '总是' })], 出口:[路由器模块] })

    【讨论】:

    • 非常感谢您的帮助:)
    猜你喜欢
    • 2019-07-06
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 2018-08-30
    • 2017-11-20
    • 1970-01-01
    • 2016-09-21
    相关资源
    最近更新 更多