首页 > 解决方案 > 如何将我的对象传递给 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'
    });
}

标签: angularloopsobjectangular-routingangular-reactive-forms

解决方案


您的代码需要少量更改 - 查看更改的注释

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'
    });
}

推荐阅读