假设我有 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/