首页 > 解决方案 > 我在 Angular FormBuilder 表单中动态检索的选择是保存为对象,而不是值

问题描述

我正在构建一个表单,它从 Cloud Firestore 中检索值列表以及其他一些选项,将它们放入下拉菜单中,并在提交时创建一个新文档。

选项显示在下拉表单中,但是当我提交它时,正在传递所有静态/本地信息,但从数据库中检索到的值仅返回对象。

如何在对象上指定字段?

component.html

  <select class="custom-select" (change)="changeProperty($event)" formControlName="meter">
  <option value="" disabled>Choose</option>
  <option *ngFor="let property of propertyList | async" [ngValue]="meter">{{property.meter}}</option>
</select>

component.ts(编辑为仅显示相关数据)

public newLeak: FormGroup;
propertyList: Observable<any>;


  constructor(
    private db: AngularFirestore,
    public fb: FormBuilder,    
  ) { }


  ngOnInit() {
    this.propertyList = this.db.collection('meters').valueChanges().pipe(map(data => data.map(d => d)));
    this.addNewLeak(); 
  }

  addNewLeak() {
    this.newLeak = this.fb.group({
      meter:[''],
    })  
  }

  changeProperty(e) {
    this.meter.setValue(e.target.value, {
      onlySelf: true
    })
  }

  get meter() {
    return this.newLeak.get('meter');
  }


  ResetForm() {
    this.newLeak.reset();
  }  

submitNewLeak() {
console.log(this.newLeak.value);
    this.db.collection('meters').doc(this.newLeak.value.meter).collection('leaks').doc(this.newLeak.value.date).set({technician: this.newLeak.value.user}, {merge: true});
    this.db.collection('meters').doc(this.newLeak.value.meter).collection('leaks').doc(this.newLeak.value.date).collection('apartments').doc(this.newLeak.value.apartment).set(this.newLeak.value);
    this.ResetForm();
   };

}

简而言之,从 UI 中一切正常,它正在将表单提交到数据库,但它正在发送一个对象而不是一个值。(我想访问该id字段或meter对象上的字段。)

谢谢你。

标签: angulargoogle-cloud-firestoreangular-formbuilder

解决方案


JSON.stringify数据保存时使用-

this.db.collection('meters').doc(this.newLeak.value.meter).collection('leaks').doc(this.newLeak.value.date).collection('apartments').doc(this.newLeak.value.apartment).set(JSON.stringify(this.newLeak.value));  // use JSON.stringify method here

推荐阅读