I am working with Angular components that execute two functions during initialization. The first function populates an array, and the second function takes values from that array and calls a service.
The issue I am facing is that the second function executes before the first one, causing the array to be empty and resulting in an error when the second function runs.
Here is the code snippet:
import { fromEvent, Subscription } from 'rxjs';
ngOnInit(): void {
this.getProducts();
this.getLoans();
}
getProducts() {
this.clientService.getClientProducts(this.clientId).subscribe(
(res) => {
if (res.success) {
this.products = res.data;
console.log('Obtaining products');
console.log(this.products);
}
}
);
}
getLoans() {
console.log('Obtaining loans');
console.log(this.products);
this.products.forEach((element) => {
if (element.id == '4') {
this.clientService.getClientLoan(this.clientId).subscribe(
(res) => {
if (res.success) {
this.loans.push(res.data);
} else {
this.hasErrorOnLoans = true;
}
},
);
}
});
}
In the console log, it is evident that the first function runs before the second one:
Apologies for any language errors! Thank you.