简体   繁体   English

Angular ReactiveForm 将 Form.Value 合并到对象

[英]Angular ReactiveForm merge Form.Value to object

Folks, I have a massive form built with Angular ReactiveForms including nested array with its own nested array.伙计们,我有一个用 Angular ReactiveForms 构建的大型表单,包括带有自己的嵌套数组的嵌套数组。

In ngOnInit() I fetch data from API:在 ngOnInit() 我从 API 获取数据:

private approval: Approval;

return this.apiService.getApproval(+id).map(data => {
   this.approval = data;
});

Next, I patch form:接下来,我修补表格:

this.form.patchValue(this.approval, { emitEvent: false });

and then on SUBMIT call然后在 SUBMIT 电话上

private onSubmit() {

  Object.assign(this.approval, this.form.value);

  return this.apiService.updateApproval(this.approval).map(data => {
  });

}

The API I am connecting to requires full object to be POST-ed, not just changes (PATCH is not implemented).我要连接的 API 需要发布完整的对象,而不仅仅是更改(未实现 PATCH)。 Therefore I may not use this.form.value , but I have to sent full object.因此我可能不会使用this.form.value ,但我必须发送完整的对象。

I am looking for something similar to .NET/C# AutoMapper.我正在寻找类似于 .NET/C# AutoMapper 的东西。 The code above - Object.assign - does what I need on first-level properties.上面的代码 - Object.assign - 在一级属性上做了我需要的事情。 Primitive types are updated, however, properties like arrays or objects are ignored.更新了原始类型,但是忽略了数组或对象等属性。

Is there any recommended 'Angular-way' how to deal with this?有没有推荐的“Angular-way”来处理这个问题? Thanks!谢谢!

EDIT: it seems like arrays are overwritten.编辑:似乎数组被覆盖了。 Objects in array have updated values, but some properties from original object, that are not present in Form, are missing.数组中的对象具有更新的值,但原始对象中的某些属性在 Form 中不存在,它们丢失了。

One option is to use Lodash merge :一种选择是使用Lodash 合并

var object = {
  'a': [{ 'b': 2 }, { 'd': 4 }]
};

var other = {
  'a': [{ 'c': 3 }, { 'e': 5 }]
};

_.merge(object, other);
// => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }

Have a look at How to deep merge instead of shallow merge for other options too.也看看如何深度合并而不是其他选项的浅合并

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM