[英]Angular how to chain functions with Observables
我有數據表,我想通過訂閱 Observables 來填充它們。 當我加載頁面時,我得到一個錯誤,因為當我想訪問它的“.cancelled”屬性時數據(financeProducts)尚未定義。 如何改進我的代碼,以便獲得函數的所有必要數據?
我試過的:
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);
};
}
將代碼放在訂閱中出現undefined
錯誤的位置。
正如@Kokogino 提到的,您可以做的另一項增強是用tap
替換map
因為您沒有轉換數據,只是分配!
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);
};
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.