Angular路由切换保留URL参数 - 保持查询字符串不变
在Angular中,当切换路由时,默认情况下,URL参数会被清除。如果你想在切换tab页时保留URL参数,你可以使用queryParamsHandling属性。\n\n1. 在路由配置中,为每个路由定义一个queryParamsHandling属性,将它设置为"preserve",这将保留所有的URL参数。\n\ntypescript\nconst routes: Routes = [\n  { path: 'tab1', component: Tab1Component, queryParamsHandling: 'preserve' },\n  { path: 'tab2', component: Tab2Component, queryParamsHandling: 'preserve' },\n  // 其他路由...\n];\n\n\n2. 在模板中的html\n<router-outlet queryParamsHandling="preserve" (activate)="reuseTab.activate($event)"></router-outlet>\n\n\n通过以上配置,当切换tab页时,URL参数将会保留,并且在URL中显示。\n\n注意:如果你使用了queryParams属性来设置URL参数,而不是通过路由导航中的queryParams参数,那么你需要在路由导航中设置queryParamsHandling为"merge",以合并新的查询参数。\n\ntypescript\nthis.router.navigate(['/tab1'], { queryParams: { param1: value1 }, queryParamsHandling: 'merge' });\n\n\n这样,新的查询参数将会与现有的查询参数合并,而不是完全替换。
原文地址: https://www.cveoy.top/t/topic/pxXc 著作权归作者所有。请勿转载和采集!