如何将我的对象传递给 Angular 6 中的 queryParams?

How can I pass my object to queryParams in Angular 6?

我正在使用 Reactive Forms 来填充我页面上的表单。当用户进行编辑和点击时应用。表单中的值被获取并应用到 url。表单字段不是必需的,用户可以返回页面并根据需要更改字段。

我正在遍历每个表单控件以查看它们的值是否为假值。如果该值不是假的,我想获取我的 select 输入的键值对并将其传递给我的 router.navigate 方法以填充 URL。我在循环内的控制台中看到了我想要的键和值对,但我不知道如何将这些值保存到对象并将其传递到 router.navigate 方法外的 queryParams 对象我的循环。相关代码如下。

为清楚起见,我不想使用本机原始值或触摸值进行检查,因为用户可以触摸表单并将其更改回默认值。另外,如果我将 router.navigate() 放在 for in 循环中,只有最后一个键和值对被添加到 URL.

我的 else 语句中的 console.log 包含用户 select 编辑的项目。我如何获取这些值并传递到我的 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'
    });
}