1

Folks, I have a massive form built with Angular ReactiveForms including nested array with its own nested array.

In ngOnInit() I fetch data from 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

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). Therefore I may not use this.form.value, but I have to sent full object.

I am looking for something similar to .NET/C# AutoMapper. The code above - Object.assign - does what I need on first-level properties. Primitive types are updated, however, properties like arrays or objects are ignored.

Is there any recommended 'Angular-way' how to deal with this? 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.

Luke1988
  • 1,850
  • 2
  • 24
  • 42

1 Answers1

0

One option is to use Lodash merge:

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.

zerocewl
  • 11,401
  • 6
  • 27
  • 53