Angular2路由器保留查询字符串

Angular2路由器保留查询字符串

本文介绍了Angular2路由器保留查询字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个使用路由器的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&param2=val2&param3=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 routerLinks and imperative navigation to enable

  • preserveQueryParams and
  • preserveFragment

您可以将保护添加到空路径路由,在保护中导航到/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.

更新说明:来自 https://angular.io/api/router/NavigationExtras ,不建议使用preserveQueryParams,请改用queryParamsHandling

Update note: from https://angular.io/api/router/NavigationExtras, preserveQueryParams is deprecated, use queryParamsHandling instead

这篇关于Angular2路由器保留查询字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 15:18