Использование значений из нескольких асинхронных вызовов, а затем выполнение вычислений для передачи значения - PullRequest
2 голосов
/ 02 октября 2019

Я делаю 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);
}

Я получаю все 3 значения objTemp.currentTemp, objTemp.desiredTempHeating, objTemp.desiredTempCooling и условия, но все они асинхронные. Как я могу присвоить значениев objTemp.tempColorToInsert после выполнения вычислений, используя вышеуказанные 4 значения.

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

customColors: any = [
    {
        color: '#50B3D3',
        temp: -1
    },
    {
        color: '#25CBE4',
        temp: -2
    },
    {
        color: '#25CBE4',
        temp: 0
    },
    {
        color: '#7EE2DD',
        temp: 1
    },
    {
        color: '#7EE2DD',
        temp: 2
    }
    ]

Обновление

Я сделал что-то подобное и получаю значения, просто хотел знать, что ответ будет автоматически сопоставлен с соответствующим элементом

   forkJoin([this.getCurrentValue(objTemp.main),this.getDesiredHeatingTemp(elementId._id),this.getDesiredCoolingTemp(elementId._id)])
        .subscribe(([current,[desiredheat], [desirecooling]])=>{
            objTemp.currentTemp = current.rows[0].val;
            objTemp.desiredTempHeating = desiredheat.rows[0].val.split(':')[1];
            objTemp.desiredTempCooling = desirecooling.rows[0].val.split(':')[1];

                let condition = 'first'

                    if(condition == 'first' ){
                        let zoneTempDiff1 = objTemp.currentTemp - objTemp.desiredTempHeating;
                        let tempColor1 = this.temperatureColors.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.temperatureColors.filter(color => zoneTempDiff2 < (color.temp + 1) && zoneTempDiff2 > (color.temp - 1));
                        objTemp.tempColorToInsert = tempColor2.color
                    }
  })

Ответы [ 4 ]

3 голосов
/ 02 октября 2019

Вы можете использовать forkJoin

const all$ = [
  this.getCurrentValue(objTemp.main),
  this.getDesiredHeatingTemp(elementId._id),
  this.getDesiredCoolingTemp(elementId._id),
  this.deviceHelper.getConditioningStatusForZone(elementId._id)
]

forkJoin(all$).subscribe(response => {
  objTemp.currentTemp = response[0].rows[0].val;
  objTemp.desiredTempHeating = response[1][0].rows[0].val.split(':')[1];
  objTemp.desiredTempCooling = response[2][0].rows[0].val.split(':')[1];
  condition = response[3];
  // now while you have all 4 values
  // Do your thing here
})
2 голосов
/ 02 октября 2019

Вы должны использовать forkJoin вместо подписки 4 раза.

Пример здесь: learnrxjs forkjoin

2 голосов
/ 02 октября 2019

Для этого вы можете использовать RxJS ZIP

И использовать его так:

zip(asyncCall_1, asyncCall_2, asyncCall_3, asyncCall_4).subscribe(
    ([asyncCall_1_response, asyncCall_2_response, asyncCall_3_response, asyncCall_4_response]) => {
        // your code goes here
    }

Таким образом, только когда все асинхронные вызовы возвращены, выНаблюдаемые выбросы

2 голосов
/ 02 октября 2019

Вы можете использовать метод forkJoin для объединения вызовов aync, а затем, когда все вызовы завершатся, использовать подписанное значение и назначить его переменной tempColorToInsert.

...