Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

angular - Angular2 router keep query string

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
    }
];

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?

Thank you
Lukas

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't think there is a way to define that in the routes configuration.

Currently it is supported for routerLinks and imperative navigation to enable

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" });

There is a PR to allow to configure preserveQueryParams globally.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...