Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 216
julianpoemp Avatar asked Dec 27 '17 16:12

julianpoemp


People also ask

How does Angular routing handle route parameters?

To access the route parameters, we use route. snapshot , which is the ActivatedRouteSnapshot that contains information about the active route at that particular moment in time. The URL that matches the route provides the productId . Angular uses the productId to display the details for each unique product.

What is Queryparams in Angular?

The query parameters feature in Angular lets you pass the optional parameters while navigating from one route to another.

How are parameters identified in the route configuration in Angular?

The first way is through the route snapshot. The route snapshot provides the initial value of the route parameter map (called the paramMap ). You can access the parameters directly without subscribing or adding observable operators. The paramMap provides methods to handle parameter access like get , getAll , and has .

How does Angular read route parameters?

Reading Route ParametersThe ProductDetails component must read the parameter, then load the product based on the ID given in the parameter. The ActivatedRoute service provides a params Observable which we can subscribe to to get the route parameters (see Observables).


Video Answer


1 Answers

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.

like image 187
Max Koretskyi Avatar answered Sep 16 '22 19:09

Max Koretskyi