使用多个异步调用中的值,然后执行计算以推送值

问题描述 投票:0回答:1

我正在进行4个异步api调用

floor.entities.forEach(elementId => {
  let objTemp: any = {};

  objTemp.main = elementId.name

  let currentTempForZone;

//1st async function
   this.getCurrentValue(objTemp.main).subscribe((curr) =>
       { 
         objTemp.currentTemp = curr.rows[0].val
        }
     );
//2nd async function
    this.getDesiredHeatingTemp(elementId._id).subscribe(([des]) =>
       {
         objTemp.desiredTempHeating = des.rows[0].val.split(':')[1]
        }
      );
//3rd async function
     this.getDesiredCoolingTemp(elementId._id).subscribe(([des]) => 
        {
          objTemp.desiredTempCooling = des.rows[0].val.split(':')[1]
          }
       );

let condition;

//4th
   this.deviceHelper.getConditioningStatusForZone(elementId._id);
   this.deviceHelper.conditioningTypeSubject.subscribe(condType => {
                                  console.log(condType);
                                  condition = condType                                    
               });

if(condition == 'first' ){
     let zoneTempDiff1 = objTemp.currentTemp - objTemp.desiredTempHeating;
     let tempColor1 = this.customColors.filter(color => zoneTempDiff1 < (color.temp + 1) && zoneTempDiff1 > (color.temp - 1));
     objTemp.tempColorToInsert = tempColor1.color
    }
else if(condition == 'second' ){
     let zoneTempDiff2 = objTemp.currentTemp - objTemp.desiredTempCooling;
     let tempColor2 = this.customColors.filter(color => zoneTempDiff2 < (color.temp + 1) && zoneTempDiff2 > (color.temp - 1));
     objTemp.tempColorToInsert = tempColor2.color
      }

      floor.droppeditem.push(objTemp);
}

我正在获取所有三个值objTemp.currentTemp,objTemp.desiredTempHeating,objTemp.desiredTempCooling和条件,但它们都是异步的使用上述4个值进行计算后,如何为objTemp.tempColorToInsert分配值。

================================================ ============================

customColors: any = [
    {
        color: '#50B3D3',
        temp: -1
    },
    {
        color: '#25CBE4',
        temp: -2
    },
    {
        color: '#25CBE4',
        temp: 0
    },
    {
        color: '#7EE2DD',
        temp: 1
    },
    {
        color: '#7EE2DD',
        temp: 2
    }
    ]
javascript angular rxjs observable rxjs6
1个回答
0
投票

您可以使用forkJoin方法合并aync调用,然后在所有调用完成后使用预订的值并将其分配给tempColorToInsert变量。


0
投票

您应该使用forkJoin而不是订阅4次。


0
投票

为此,您可以使用RxJS ZIP

© www.soinside.com 2019 - 2024. All rights reserved.