angular - 我在 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
对象上的字段。)
谢谢你。
解决方案
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
推荐阅读
- c# - 任务结果总是返回 null
- powerbi - 按月或年计算员工人数
- matlab - MATLAB 三重积分的问题
- r - 某些条件下的累计
- python - 使用 df.to_excel 将按钮插入电子表格
- c# - 由于我不太理解的错误而无法构建 - “ReferencePath”没有定义元数据“CopyLocal”的值
- java - 为什么我不能导入 javafx,即使我已经为 eclipse 安装了 e(fx)clipse
- asp.net-core - 从 .Net core Web Api 生成和下载 excel 文件返回 500 错误
- mysql - 如何为每个现有记录创建新记录并将现有记录引用到新创建的记录?
- javascript - onclick 函数 getInc 未定义