【发布时间】:2019-03-09 09:47:19
【问题描述】:
我有一个嵌套操作,以便首先删除报价,然后将其再次保存为重复报价。
问题是,保存重复报价后,我想patchValue()offerList[index]中的项目。这是我得到错误的地方:
错误:必须为表单控件提供一个值,名称为:'id'。
然而,调试显示一切都应该没问题。最终订阅中的对象saved 设置了有效字段。 id 存在且不为空:
this._offerService.remove(this.placeId, offer)
.pipe(
flatMap((removed: OfferModel) => {
// Re-use the removed offer to save a repeating one
removed.id = null;
removed.repeatWeekly = true;
return this._offerService.save(this.placeId, removed)
.pipe(finalize(() => this.updateOffersFormArray()));
}),
)
.subscribe(
(saved) => {
console.log(saved);
// offerList is either this.offers or this.repeatingOffers
offerList[index].patchValue(saved);
});
控制台将记录:
{id: 55, offerDate: "2019-03-04", …}
这就是updateOffersFormArray()中发生的事情:
// this.offersFormArray is a FormArray
updateOffersFormArray() {
const tmp = this.repeatingOffers.concat(this.offers);
console.log(tmp);
this.offersFormArray.setValue(tmp); // <-- Throws error
}
控制台输出向我显示了一个 FormGroup 元素的数组,正如预期的那样,这些 FormGroup 元素中的每个 value 都有一个包含所有值的报价 - 特别是 id - 这是根据未设置错误消息。
我已经为此苦苦思索了很长一段时间,但我只是看不到它。
我知道代码看起来有点奇怪。在updateOffersFormArray() 执行后,this.offersFormArray 的状态更改事件将更新this.offers 和this.repeatingOffers,这是我显示所需的。只是为了完成图片,这是执行此操作的代码:
this.offersFormArray.statusChanges.subscribe((e) => {
const offers: Array<AbstractControl> = [];
const repeatingOffers: Array<AbstractControl> = [];
for (const k of Object.keys(this.offersFormArray.controls)) {
const offerForm = this.offersFormArray.controls[k];
const offer = <OfferModel> offerForm.value;
if (offer.repeatWeekly) {
repeatingOffers.push(offerForm);
} else {
offers.push(offerForm);
}
}
this.offers = offers;
this.repeatingOffers = repeatingOffers;
});
【问题讨论】:
标签: angular typescript