How to keep query parameters in angular 5 on all routes by default?

geronimo678 picture geronimo678 · Dec 27, 2017 · Viewed 7.9k times · Source

Background:

The user calls the app's url with the parameters and uses my app. While switching between different routes the url parameters should be kept visible in the browser's address bar.


I have to keep the query parameters on each route of my app. That means if I have the url

www.example.com/app/test?id=326748798342&state=1

and call a link with [routerLink]="['/login']" I have to get this url:

www.example.com/app/login?id=326748798342&state=1.

On default I get the login route without the parameters. I found one solution that says to set queryParamsHandling='merge'. But this is a very bad solution because that would mean to change all links in templates and all navigate() calls.

Is there a cleaner way to solve this problem on default? Something such setting queryParamsHandling in the routes array for the app or something else?

Answer

Max Koretskyi picture Max Koretskyi · Dec 27, 2017

Currently there is no way to set it globally. Using queryParamsHandling seems to be the only option:

<a [routerLink]="['/login']" queryParamsHandling="preserve"></a>

Or when using router:

router.navigate('/login', { queryParamsHandling: "preserve" })

The other possible option for queryParamsHandling is merge.