[英]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. 在我的Angular应用程序中,我有一个多字段的Reactive Form,用户可以使用它来搜索我们的内部数据库。
When the user clicks "Search" I want to route to a SearchResultsComponent
to display the results. 当用户单击“搜索”时,我想路由到
SearchResultsComponent
以显示结果。 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 基本上,正如我想象的那样,访问
https://carsuniverse.com/?make=Honda&model=Civic&year=2009
应激活SearchResultsComponent
,后者又调用执行搜索的服务,将其返回到组件并在页面上显示
What is the best (or a good way at least) to do this in Angular? 在Angular中做到这一点最好(或者至少是好方法)是什么?
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. 我们获取作为表单值的对象,对于每个键,我们将值附加到
URLSearchParams
对象,然后可以在发出请求时将其传递给Http
库。
You may want to think about the implications of this if the form is deeply nested. 如果表单深层嵌套,您可能想要考虑这个含义。
UPDATE UPDATE
If you want deeply nested forms to be represented in the query params, you'll have to modify the for
loop slightly. 如果要在查询参数中表示深层嵌套表单,则必须稍微修改
for
循环。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.