Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Angular 4, how do you convert a FormGroup into a URL with query parameters?

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?

like image 587
CodyBugstein Avatar asked Oct 27 '17 18:10

CodyBugstein


People also ask

Can post URL have query parameters?

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.

What is URL query parameter?

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.

What is query component in URL?

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).


1 Answers

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+Ranc‌​hers
like image 185
Lansana Camara Avatar answered Sep 28 '22 06:09

Lansana Camara