I am using mat-stepper single form for my stepper. when i do API call it sends data as an array of objects like this:
JavaScript
x
15
15
1
[
2
{
3
"product": "lifeci",
4
"gender": "F",
5
"birthDate": "1999-04-23T10:58:53.839Z",
6
"payFrequency": 12,
7
"subLimit": "100"
8
},
9
{
10
"currency": "USD",
11
"amount": "15000",
12
"period": 3
13
}
14
]
15
I would like to send data as one object like this:
JavaScript
1
11
11
1
{
2
"gender": "string",
3
"birthDate": "2021-04-23T11:37:01.738Z",
4
"period": 0,
5
"payFrequency": 0,
6
"amount": 0,
7
"subLimit": "string",
8
"currency": "string",
9
"product": 0
10
}
11
this is my form:
JavaScript
1
28
28
1
this.formGroup = this._formBuilder.group({
2
formArray: this._formBuilder.array([
3
this._formBuilder.group({
4
product: ['lifeci', Validators.required],
5
gender: ['', Validators.required],
6
birthDate: ['', [Validators.min(18), Validators.max(50)]],
7
payFrequency: [12],
8
subLimit: ['100']
9
}),
10
this._formBuilder.group({
11
currency: ['USD', Validators.required],
12
amount: ['15000', Validators.required],
13
period: ['', Validators.required],
14
}),
15
])
16
});
17
18
onSubmit() {
19
this.service.calculate(this.formGroup.value).subscribe(
20
(res:any)=>{
21
console.log(res);
22
},
23
err => {
24
console.log(err);
25
}
26
);
27
}
28
service.ts
JavaScript
1
12
12
1
export class LifeciService {
2
3
readonly API_SERVER = "API_URL";
4
constructor(private http: HttpClient) { }
5
6
calculate(formData) {
7
return this.http.post(this.API_SERVER + '/Calculate', formData);
8
}
9
10
11
}
12
how can i do it?
Advertisement
Answer
You can use a simple transformation using javascript reduce
function to transform the data to the desired structure
JavaScript
1
4
1
const initial = [ { "product": "lifeci", "gender": "F", "birthDate": "1999-04-23T10:58:53.839Z", "payFrequency": 12, "subLimit": "100" }, { "currency": "USD", "amount": "15000", "period": 3 } ];
2
3
const reduced = initial.reduce((prev, next) => ({prev, next}), {})
4
console.log(reduced)
In your case this can be implemented like below
JavaScript
1
12
12
1
onSubmit() {
2
const formArrayData = this.formGroup.get('formArray').value;
3
const data = formArrayData.reduce((prev, next) => ({prev, next}), {})
4
this.service.calculate(data).subscribe(
5
(res:any)=>{
6
console.log(res);
7
},
8
err => {
9
console.log(err);
10
}
11
);
12