I have an observable made from an array of form controls in Angular. I am using dropdowns and inputs to calculate the sum of all currencies in relation to one currency, and it works. However, my issue is that when I want to update the field itself, the value of the sum is not changed immediately due to an HTTP request delay. I need to set the value of the field only when all the code has finished executing and the sum has its final form.
let sum = 0;
let arrayOfControls = [];
for (let control of this.currencies.controls) {
arrayOfControls.push(control);
}
const myObservable = from(arrayOfControls);
const myObserver = {
next: (control) => {
let currency = control.get('dropdown').value;
let amount = Number(control.get('amount').value);
if (currency && amount) {
this.updateRate(currency).subscribe((serverData) => {
let rate = serverData['rates'][this.dropdown2.value];
sum += amount * rate;
// The sum changes here.
});
}
},
complete: () => {
// When trying to set the value of the field, the sum may not have changed yet due to the delay.
this.amount2.setValue(sum.toFixed(2));
},
};
myObservable.subscribe(myObserver);