Angular2 路由器保留查询字符串 [英] Angular2 router keep query string
问题描述
我编写了一个使用路由器的 Angular2 (v2.0.1) 应用程序.该网站加载了多个查询字符串参数,因此完整 URL 最初如下所示:
I wrote an Angular2 (v2.0.1) application that makes use of the router. The website is loaded with several query string parameters, so the full URL initially looks like this:
https://my.application.com/?param1=val1¶m2=val2¶m3=val3
在我的路由配置中,我有一个重定向空路由的条目:
In my route configuration, I have an entry which redirects an empty route:
const appRoutes: Routes = [
{
path: '',
redirectTo: '/comp1',
pathMatch: 'full'
},
{
path: 'comp1',
component: FirstComponent
},
{
path: 'comp2',
component: SecondComponent
}
];
我的问题是,在应用程序启动后,URL 不再包含查询参数,而是如下所示:
My problem is, that after the app has been bootstrapped, the URL does not contain the query parameters anymore, instead it looks like this:
https://my.application.com/comp1
有什么办法可以配置路由器,使其在导航时保留初始查询字符串?
Is there any way I can configure the router so that it keeps the initial query string when navigating?
谢谢
卢卡斯
推荐答案
我认为没有办法在路由配置中定义它.
I don't think there is a way to define that in the routes configuration.
目前支持routerLink
s和命令式导航启用
Currently it is supported for routerLink
s and imperative navigation to enable
您可以为空路径路由添加一个守卫,在守卫中导航到 /comp1
路线.
You can add a guard to the empty path route, where in the guard navigation to the /comp1
route is done.
router.navigate(['/comp1'], { preserveQueryParams: true }); //deprecated. see update note
router.navigate(['/comp1'], { queryParamsHandling: "merge" });
有一个 PR 允许配置 preserveQueryParams
全球.
There is a PR to allow to configure preserveQueryParams
globally.
更新说明:来自https://angular.io/api/router/NavigationExtras,preserveQueryParams 已弃用,改用 queryParamsHandling
Update note: from https://angular.io/api/router/NavigationExtras, preserveQueryParams is deprecated, use queryParamsHandling instead
这篇关于Angular2 路由器保留查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!