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?
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.
The query parameters feature in Angular lets you pass the optional parameters while navigating from one route to another.
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 .
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).
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With