代码之家  ›  专栏  ›  技术社区  ›  London804

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

  •  0
  • London804  · 技术社区  · 6 年前

    我正在使用反应式表单填充页面上的表单。当用户进行编辑并单击“应用”时。表单中的值被获取并应用到url。表单字段不是必需的,用户可以返回页面并随意更改字段。

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

    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'
        });
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Sunil Singh    6 年前

    你的代码需要一些小的改动-看看注释中的改动

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