How to keep query string parameters in URL when accessing a route of an Angular 2 app?
Asked Answered
O

3

3

I have an Angular 2 test app running the latest alpha (37). There are just three routes, that look like this:

@RouteConfig([
  { path: '/', component: Home, as: 'home' },
  { path: '/errors', component: Errors, as: 'errors' },
  { path: '/about', component: About, as: 'about' }
])

I can access the routes, and when I place query string params in the URL I can read them just fine. However, a few instants after I read the parameters, I noticed that the route loads fine and the URL refreshes, removing the query string parameters.

In other words, accessing this route:

http://localhost:5555/errors?test=abc

Loads the /errors route, but right after the application loads the URL turns into:

http://localhost:5555/errors

That would be confusing to a user. I would like to keep the query string parameters in the URL.

I know, it's in alpha, but is this a bug or I forgot to set something up on the router? How can I keep whatever query string parameters in the URL?

Thanks!

Orlando answered 28/9, 2015 at 5:47 Comment(0)
F
1

This is fixed in Alpha 41. The query string is now persisted.

Frictional answered 14/10, 2015 at 14:50 Comment(3)
I got exactly the same problem in Angular 2.0.0 beta 12Reduction
@aokaddaoc Can't reproduce in beta 15. This was the original issue github.com/angular/angular/issues/4413. Feel free to comment there or open another issue.Frictional
Reproduced on Angular 4.3.1, 4.4.6 and 5.0.4: #47599262Radiophone
M
1

Updating for Angular 2:
To preserve query parameters present in the current url, add

// import NavigationExtras 
import  { NavigationExtras } from '@angular/router';

// Set our navigation extras object
// that contains our global query params

let navigationExtras: NavigationExtras = {
      preserveQueryParams: true
    };   

// Navigate to the login page with extras
this.router.navigate(['/someLink'], navigationExtras);

For more info, check here:

Matheson answered 21/11, 2016 at 7:11 Comment(1)
This won't work for direct linking from outside of the site though.Favorite
R
0

Try this this.router.navigate(['target'], {preserveQueryParams: true});

Rhine answered 23/11, 2016 at 9:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.