I have encountered a challenge during the development of an application using Angular 6. When passing an object as a value of a property in queryParams: { prop: value}
, the built-in function converts the object to a string, resulting in the common JavaScript output of [object Object]
.
My goal is to utilize my query string for updating the query parameters of the current route. Here's an example of my query string stringified with npm-qs library:
?priceRange[min]=1&priceRange[max] = 2
Now, let's consider the object that I parse using the same library and convert back to an object:
priceRange: {min: "1", max: "2"}
However, queryParams
converts it to:
priceRange=%5Bobject%20Object%5D
To resolve this issue, I reparse it into a proper object and then use a method outlined below:
constructor(
private readonly router: Router,
private readonly activatedRoute: ActivatedRoute,
) {}
updateQueryParams() {
this.router.navigate([], {
relativeTo: this.activatedRoute,
queryParams: {
priceRange: {min: "1", max: "2"} (hardcoded this to simplify example)
}
});
}
The above code aims to:
Stay on the same page (
[]
along withrelativeTo: this.activatedRoute
allows me to remain on the current page);Adjust the URL to
.com/?priceRange[min]=1&priceRange[max]=2
Is there a way to successfully use objects as values in queryParams or any other suggestions? I have reviewed the documentation on angular.io, but it does not cover such cases, only providing simple examples like param1=q & param2=w
, similar to various posts on Stack Overflow. Perhaps there is a different method within Angular to pass a query string to the URL without using the queryParams
of the router.navigate()
method.
Thank you in advance!