I have datatables, and I would like to fill them by subscribing to Observables. When I load the page, I get an error, because the data (financeProducts) is not yet defined when I would like access its ".cancelled" property. How can I improve my code so that I get all the necessary data for the functions?
What I have tried:
ngOnInit() {
this.setUpData();
}
setUpData() {
forkJoin([this.financeStatusService.getProducts(), this.accountService.getAccounts()])
.pipe(
map(([products, accounts]) => {
this.financeProducts = products;
this.accountsList = accounts;
})
).subscribe();
if (this.financeProducts.cancelled) {
...
} else {
...
this.setFinanceTableRows(this.financeProducts);
}
}
setFinanceTableRows(product) {
const finRow: FinRowWithID = {
accountName: product.name,
...
id: this.accountsList.filter(entry => entry.id);
};
}
CodePudding user response:
Put the code where you are getting the undefined
error inside the subscribe.
as @Kokogino mentioned, another enhancement you can do is substitute map
with tap
since you are not transforming the data, just assigning!
setUpData() {
forkJoin([this.financeStatusService.getProducts(), this.accountService.getAccounts()])
.pipe(
tap(([products, accounts]) => {
this.financeProducts = products;
this.accountsList = accounts;
})
).subscribe(() => {
if (this.financeProducts.cancelled) {
// ...
} else {
// ...
this.setFinanceTableRows(this.financeProducts);
}
});
}
setFinanceTableRows(product) {
const finRow: FinRowWithID = {
accountName: product.name,
// ...
id: this.accountsList.filter(entry => entry.id);
};
}