从反应形式valueChanges

时间:2018-11-05 08:46:28

标签: angular rxjs angular-reactive-forms

我在角度应用中有反应形式。我订阅 valueChanges ,并且在获取 subscribe 方法的结果之前,想使用rxjs filter 或类似方法过滤该对象,以仅获得形成。我该怎么解决?

this.form.valueChanges.pipe(
     debounceTime(500),
     filter(formObj => {
     // code that remove empty object values
     })
).subscribe(val => {
  // val example `{fullName: "name", dateOfBirthday: "", phoneNumber: "", fullAddress: ""}`       
});

1 个答案:

答案 0 :(得分:3)

已经创建了Stackblitz Demo供您参考

您可以以某种方式实现它:

filterEmptyFields(data: any): any {    // Filter any fields that aren't empty & store in a new object - To be passed on the Pipe map's caller
    let fields = {};
    Object.keys(data).forEach(key =>  data[key] != '' ? fields[key] = data[key] : key);

    return fields;   
}

trackEmptyFields(): void {
    this.form
      .valueChanges
      .pipe(map(this.filterEmptyFields))
      .subscribe(fields => console.log(fields));    
}

Stackblitz Demo的输出

enter image description here