[英]Angular: Ensure Services is Complete before Running Next Step
我們目前正在使用 Angular。 組件正在從 API 接收數據。 在獲得 API 數據后,它會通過數據服務來轉換和自定義數據、連接名字、四舍五入、進行計算等。最后一步嘗試在解析所有數據后在下拉列表中填充銷售年份。
this.webStoreSearchHttpService.GetAllCustomerSalesData(this.customerId).subscribe((response) => {
this.customerList= customerDataService.createCustomerList(response);
this.productList = customerDataService.createProductAnalysis(response);
this.salesList= customerDataService.createSalesList(response);
this.salesYearList= customerDataService.createYearList(response);
this.salesYearItemCurrent = _.cloneDeep(this.salesYearList[0]); <--- this goes into a Mat Select Dropdown
但是,在選擇 web 下拉菜單后,相關數據不會出現,因為數據服務尚未完成解析/創建,即使它在原始 API 訂閱中也是如此。
我正在嘗試做的是確保所有 4 項數據服務都完全完成,然后填充 salesYear。 如何使用 Angular typescript 做到這一點?
數據服務可以並行運行,但最后一步是下拉列表中的 salesYear 人口。
這些方法返回 class arrays,而不是 promises 或 observables。
更新
您添加了語句The methods return class arrays, not promises or observables.
. 這意味着您不可能從外部等待異步調用完成。 因此,您必須更改customerDataService
方法的返回值。 我假設在這個方法中完成了一些異步的工作,因為你說What I am trying to do, is make sure all 4 Data services are totally complete
。
舊版
要回答您的問題,必須知道customerDataService
方法的返回類型是什么。 該方法是否返回Promise
或Observable
? 根據這一點,您可以使用Promise.all
或forkJoin
運算符等待所有方法完成,然后執行 select 填充。 這是一個使用 observables 的例子:
this.webStoreSearchHttpService.GetAllCustomerSalesData(this.customerId).subscribe(response => {
forkJoin([
customerDataService.createCustomerList(response),
customerDataService.createProductAnalysis(response),
customerDataService.createSalesList(response),
customerDataService.createYearList(response)
]).subscribe(([customerList, productList, salesList, salesYearList]) => {
this.customerList = customerList;
this.productList = productList;
this.salesList = salesList;
this.salesYearList = salesYearList;
this.salesYearItemCurrent = _.cloneDeep(this.salesYearList[0]);
});
});
甚至更好地避免內部訂閱並且只有一個訂閱:
this.webStoreSearchHttpService.GetAllCustomerSalesData(this.customerId).pipe(
flatMap(response =>
forkJoin([
customerDataService.createCustomerList(response),
customerDataService.createProductAnalysis(response),
customerDataService.createSalesList(response),
customerDataService.createYearList(response)
])
)
).subscribe(([customerList, productList, salesList, salesYearList]) => {
this.customerList = customerList;
this.productList = productList;
this.salesList = salesList;
this.salesYearList = salesYearList;
this.salesYearItemCurrent = _.cloneDeep(this.salesYearList[0]);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.