在 forEach 循环中调用 Angular 服务 [英] Call Angular service inside forEach loop

查看:43
本文介绍了在 forEach 循环中调用 Angular 服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Angular 4 的初学者.我想以欧元计算总发票,我有每个价格的价格和货币类型的价值.当我想计算总金额时,我需要调用 exchangeService 服务,以获得货币的汇率.

I am beginner in Angular 4. I want to calculate total invoice in EUR curency, I have value of prices and currenciy type for each price. When I want to calculate total sum, I need to call exchangeService service , in order to get exchange rate of currency.

当我检查 invoicesSumTotalValue 的值为 0 时.这是我的代码:

When I inspect the value of invoicesSumTotalValue it is 0. Here is my code:

    calcInvTotalValue(){

     let prods = (<FormArray>(<FormGroup>(<FormArray>this.productData.parent.parent).parent).controls['products']);
        let invoicesSumTotalValue = 0;


        prods.controls.forEach(c => {
          let price = (<FormGroup>(<FormGroup>c).controls['selected_products']).controls['price'].value;
          let currency = (<FormGroup>(<FormGroup>c).controls['selected_products']).controls['currency'].value;

          this.exchangeService.getExchRate(currency, "USD").subscribe(
            vl => {
              let exRate = vl;
              invoicesSumTotalValue = invoicesSumTotalValue + (parseFloat(price) * exRate);
            },
            (error: any) => console.log(error)
          );
        });
        console.log("iNVOICE total is: " + invoicesSumTotalValue);

如何为 prods 数组的每个值调用服务?谢谢!

How can I call service for each value of prods array ? Thank you!

推荐答案

你应该使用 RxJS 的 forkJoin 等待 Array.forEach() 循环完成,然后返回所有可观察对象.如果你熟悉 Promises 在 JavaScript 中的使用,其实和 Promise.all.

You should make use of RxJS's forkJoin to wait for the Array.forEach() loop to be completed before returning all the observables. If you are familiar with the usage of Promises in JavaScript, it is actually similar to Promise.all.

您将面临计算 invoicesSumTotalValue 的问题,因为 observables 的返回是一个异步操作,因此 forEach 循环的下一次迭代很可能会在响应之前执行从 getExchRate() 返回.

You will face issues calculating invoicesSumTotalValue because the returning of observables is an asynchronous operation, hence it is likely the next iteration of the forEach loop will be executed before the response from getExchRate() is returned.

这是我对您的代码的建议修改.基本上,一旦 forEach() 循环的所有迭代都完成,我们使用 forkJoin() 返回可观察值.从那里,在返回可观察值的 subscribe() 块中,我们处理 invoicesSumTotalValue 的计算.

Here is my suggested modifications to your code. Basically, we make use of forkJoin() to return the observables once all iterations of the forEach() loop have been completed. From there, within the subscribe() block where we return the observables, we handle the calculation of invoicesSumTotalValue.

const prods = (<FormArray>(<FormGroup>(<FormArray>this.productData.parent.parent).parent).controls['products']);
const observablesList = [];

prods.controls.forEach(c => {
  const currency = (<FormGroup>(<FormGroup>c).controls['selected_products']).controls['currency'].value;
   observablesList.push(this.exchangeService.getExchRate(currency, 'USD'));
})

forkJoin(observablesList).subscribe(response => {
  //console.log(response);
  // handle the rest
});

这篇关于在 forEach 循环中调用 Angular 服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆