angular - 如何将我的对象传递给 Angular 6 中的 queryParams?
问题描述
我正在使用响应式表单在我的页面上填充表单。当用户进行编辑和点击时应用。表单中的值被获取并应用于 url。表单字段不是必需的,用户可以返回页面并根据需要更改字段。
我正在遍历每个表单控件以查看它们的值是否虚假。如果值不是假的,我想获取我的选择输入的键和值对并将其传递给我的 router.navigate 方法以填充 URL。我在循环内的控制台中看到了我想要的键和值对,但我不知道如何将这些值保存到一个对象并将其传递给我循环外 router.navigate 方法中的 queryParams 对象. 相关代码如下。
为清楚起见,我不想使用原生原始值或触摸值进行检查,因为用户可以触摸表单并将其更改回默认值。此外,如果我将 router.navigate() 放在 for in 循环中,则只会将最后一个键和值对添加到 URL。
我的 else 语句中的 console.log 包含用户选择的项目。如何获取这些值并传递给我的 router.navigate() 中的 queryParms?
addExtraParameters() {
for (var key in this.providerForm.controls) {
this.x = this.providerForm.get(key).value
if (!this.x || this.x === "null") {
// this removes items that were not touched or edited
} else {
console.log(key, this.x);
}
}
this.router.navigate([],
{ queryParams: {
[key]: this.x // this doesn't work
}, queryParamsHandling: 'merge'
});
}
解决方案
您的代码需要少量更改 - 查看更改的注释
addExtraParameters() {
var params = {}; //create new param object
for (var key in this.providerForm.controls) {
let x = this.providerForm.get(key).value; //create local variable.
if (!x || x === "null") {
// this removes items that were not touched or edited
} else {
console.log(key, x);
params[key] = x; //add new param key and value to existing params
}
}
this.router.navigate([],
{ queryParams: params, queryParamsHandling: 'merge'
});
}
推荐阅读
- flutter - 图像未在 Flutter Draw Header 上加载
- flask - Cloud Run 中部署的烧瓶 API 中的请求不起作用
- json - 快速解码 JSON 文件时遇到问题
- python - 两个不同长度的numpy数组的笛卡尔求和
- python - os.listdir 显示 25000 个输入,但只能加载 10685 个文件
- python - 如果两个dict中的列表元素共享任何元组,则获取键值
- java - 如何在约束布局中添加浮动按钮
- authorize.net - 如何在授权前进行信用卡验证
- javascript - 为什么 esprima 在在线浏览器演示中运行良好,但在本地失败
- opencv - 如何构建只支持解码jpeg的opencv?