Angular:确保服务在 运行 下一步之前完成

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 下拉列表后,关联数据不会出现,因为数据服务尚未完成 parsing/created,即使它是原始的 API 订阅。

我要做的是确保所有 4 个数据服务都完全完成,然后填充 salesYear。如何使用 Angular typescript 完成此操作?

数据服务可以运行并行,但最后一步是下拉列表中的销售年份人口。

方法 return class 数组,不是 promises 或 observable。

更新

您添加了句子 The methods return class arrays, not promises or observables.。这意味着您不可能从外部等待异步调用完成。因此,您必须更改 customerDataService 方法的 return 值。我假设在这个方法中完成了一些异步的事情,因为你说 What I am trying to do, is make sure all 4 Data services are totally complete.

旧版本

要回答您的问题,您必须知道 customerDataService 方法 return 类型是什么。做方法return Promise还是Observable?取决于您可以使用 Promise.allforkJoin 运算符等待所有方法完成,然后执行 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]);
});