In my Angular app, I have a multifield Reactive Form which users can use to search our internal database.
When the user clicks "Search" I want to route to a SearchResultsComponent
to display the results. I also want the route in the browser to contain query parameters that represent the form input, so the user can copy it somewhere and re-use it easily. Essentially, as I imagine it, visiting https://carsuniverse.com/?make=Honda&model=Civic&year=2009
should activate the SearchResultsComponent
which in turn calls a service that performs the search, returns it to the component and displays it on the page
What is the best (or a good way at least) to do this in Angular?
POST should not have query param. You can implement the service to honor the query param, but this is against REST spec. "Why do you pass it in a query param?" Because, like for GET requests, the query parameters are used to refer to an existing resource.
Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.
On the internet, a Query string is the part of a link (otherwise known as a hyperlink or a uniform resource locator, URL for short) which assigns values to specified attributes (known as keys or parameters).
Try this:
const params = new URLSearchParams();
const formValue = this.form.value; // this.form should be a FormGroup
for (const key in formValue) {
params.append(key, formValue[key]);
}
We grab the object that is the form value, and for each key we append the value to a URLSearchParams
object, which can then be passed to the Http
library when making requests.
You may want to think about the implications of this if the form is deeply nested.
UPDATE
If you want deeply nested forms to be represented in the query params, you'll have to modify the for
loop slightly. But here is an example of how your query might look for deeply nested objects:
{
name: 'John',
favorites: {
food: 'Pizza',
candy: 'Jolly Ranchers'
}
}
The object above could be represented like this:
?name=John&favorites[food]=Pizza&favorites[candy]=Jolly+Ranchers
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