javascript - 如何在 Angular 中的查询参数更改时重用路由,但不在路径参数更改时重用?

标签 javascript angular angular-router

假设我有 2 条路线 '/users'/users/:id。第一个渲染 UserListComponent,第二个渲染 UserViewComponent

我想在从 /users/1 导航到 /users/2 时重新渲染组件。当然,如果我从 /users 导航到 /users/1,反之亦然。

但是如果我从 /users/1?tab=contacts 导航到 /users/1?tab=accounts,我不想重新渲染组件。

有没有办法为整个应用程序配置这样的路由器?

--

更新:

我正在 AppRoutingModule 中导入 RouterModule,如下所示:

RouterModule.forRoot(routes, {relativeLinkResolution: 'legacy' })

我正在使用 Angular 12

最佳答案

Angular 路由器的默认行为是当 URL 与当前路由匹配时保留当前组件。

可以使用 onSameUrlNavigation 更改此行为选项:

Define what the router should do if it receives a navigation request to the current URL. Default is ignore, which causes the router ignores the navigation. This can disable features such as a "refresh" button. Use this option to configure the behavior when navigating to the current URL. Default is 'ignore'.

不幸的是,这个选项的粒度不够细,无法允许重新加载路径参数和忽略查询参数。

因此,您必须同时订阅查询参数和路径参数,如下所示:

constructor(route: ActivatedRoute) { }

ngOnInit() {
  this.renderLogic();
  this.route.params.subscribe(() => this.renderLogic());
  this.route.queryParams.subscribe(() => this.renderLogic());
}

renderLogic() {
  // ...
}

关于javascript - 如何在 Angular 中的查询参数更改时重用路由,但不在路径参数更改时重用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68935004/

相关文章:

javascript - HTML 输入值中的文字引号

javascript - 谷歌地理编码 API

javascript - Django - AngularJs 项目结构

html - 在最小化浏览器期间,网格标题将隐藏在 p-dialog 中

angular - NativeScript-Angular -> app.component.ts 中的 ActionBar 路由变化时不一致

angular - 如何让守卫订阅 Angular 2 中服务的长轮询请求

javascript - 如何在 window.open 方法中将动态 PHP 变量作为参数传递

javascript - node-sass 安装问题

javascript - 获取最接近组件 Angular 5 的元素

Angular RouteReuseStrategy 滚动位置保持