简体   繁体   English

如何比较 Firebase 实时数据库的两个孩子?

[英]How to compare two children of Firebase Realtime Database?

Based on the result of data.key === "high_temp_coil" , I am printing the data into my webpage with data.val() as shown below:基于data.key === "high_temp_coil"的结果,我使用data.val()将数据打印到我的网页中,如下所示:

var deviceRef = app.database().ref('/'+localStorage.getItem('machineid'));
deviceRef.on('child_added', function(data) {
  if (data.key === 'high_temp_coil') {
    $('#high_temp_coil .value').html(data.val())
  }
  if (data.key === 'low_temp_coil') {
    $('#low_temp_coil .value').html(data.val());
  }
}

In my code high_temp_coil represents the high temperature of the coil and low_temp_coil represents the low temperature of the coil, each with their own fields in my database.在我的代码中, high_temp_coil代表线圈的高温, low_temp_coil代表线圈的低温,它们在我的数据库中都有自己的字段。 However, due to a manufacturing issue, sometimes the high temp and low temps are backwards and I need to figure this out before printing the data.然而,由于制造问题,有时高温和低温是倒退的,我需要在打印数据之前弄清楚这一点。 This is how I was trying to do that but it doesn't work:这就是我尝试这样做的方式,但它不起作用:

if (data.key === "high_temp_coil"){
  let valueh= data.val(); 
  if (data.key === "low_temp_coil"){
    let valuel= data.val()
    console.log(valueh);
    console.log(valuel);
  }
}

This is what the data looks like in my database:这是数据在我的数据库中的样子:

{
  "MachineNo": {
    "water": "value"
    "high_temp_coil": "value"
    "low_temp_coil": "value"
  }
}

When you use a child_added event listener, your callback will be invoked whenever one of the children under that database location changes.当您使用child_added事件侦听器时,只要该数据库位置下的其中一个子项发生更改,就会调用您的回调。 Using this, you would need to store high_temp_coil and low_temp_coil in variables outside of the function so that you can compare them properly.使用它,您需要将high_temp_coillow_temp_coil存储在 function 之外的变量中,以便您可以正确地比较它们。 Because you store the result in an element, you could pull the current values from there.因为您将结果存储在一个元素中,所以您可以从那里提取当前值。

Note: In the below snippets I follow the convention of naming the DataSnapshot object as snapshot , reserving data for the plain JavaScript object returned by snapshot.val() .注意:在下面的代码片段中,我遵循将DataSnapshot object 命名为snapshot的约定,为snapshot.val()返回的普通 JavaScript object 保留data This aids in preventing confusion later on, especially when not using TypeScript.这有助于防止以后出现混淆,尤其是在不使用 TypeScript 时。

var deviceRef = app.database().ref('/'+localStorage.getItem('machineid'));
deviceRef.on('child_added', function(snapshot) {
  if (snapshot.key === 'high_temp_coil') {
    const newHighTempValue = snapshot.val();
    const lowTempValue = $('#low_temp_coil .value').html();
    if (Number(newHighTempValue) >= Number(lowTempValue)) { // <- assuming the values are numeric and not written as "52.1°C"
      // new value is higher than current value
      $('#high_temp_coil .value').html(newHighTempValue)
    } else {
      // new value is lower than current value, swap places
      $('#high_temp_coil .value').html(lowTempValue)
      $('#low_temp_coil .value').html(newHighTempValue)
    }
  }
  if (snapshot.key === 'low_temp_coil') {
    const newLowTempValue = snapshot.val();
    const highTempValue = $('#high_temp_coil .value').html();
    if (Number(newLowTempValue) < Number(highTempValue)) { // <- assuming the values are numeric and not written as "52.1°C"
      // new value is lower than current value
      $('#low_temp_coil .value').html(newLowTempValue)
    } else {
      // new value is higher than current value, swap places
      $('#low_temp_coil .value').html(highTempValue)
      $('#high_temp_coil .value').html(newLowTempValue)
    }
  }
}

The main issue with the above code is that the child_added events would fire once on page load, and not get live updates from any sensors updating the data because these changes would fire child_changed events.上述代码的主要问题是child_added事件会在页面加载时触发一次,并且不会从更新数据的任何传感器获得实时更新,因为这些更改会触发child_changed事件。

However, for your data structure, you can greatly simplify your code by listening to value events instead.但是,对于您的数据结构,您可以通过监听value事件来大大简化您的代码。 These listeners will be fired each time any of the data under that location is updated - including when a machine is created and any changes to the temperatures.每次更新该位置下的任何数据时都会触发这些侦听器 - 包括创建机器时和温度发生任何变化时。 Also, because the data is one level higher in the tree, you have access to the latest high_temp_coil and low_temp_coil values right in the snapshot.此外,由于数据在树中高一级,因此您可以在快照中访问最新的high_temp_coillow_temp_coil值。 The trade-off for this listener is that you need to make sure to handle when the data does not exist ( snapshot.exists()===false ) because child_added listeners would only be invoked when data is created where it is guaranteed to exist.此侦听器的权衡是您需要确保在数据不存在时进行处理( snapshot.exists()===false ),因为child_added侦听器只会在保证存在的数据创建时被调用.

var deviceRef = app.database().ref('/'+localStorage.getItem('machineid'));
deviceRef.on(
  'value',
  function(snapshot) {
    if (!snapshot.exists()) {
      // TODO: handle machine does not exist
      console.error(`Machine ${localStorage.getItem('machineid')} does not exist in database`);
      return;
    }

    const data = snapshot.val();
    const highTempValue = data.high_temp_coil;
    const lowTempValue = data.low_temp_coil;

    if (Number(highTempValue) >= Number(lowTempValue)) { // <- assuming the values are numeric and not written as "52.1°C"
      $('#high_temp_coil .value').html(highTempValue)
      $('#low_temp_coil .value').html(lowTempValue)
    } else {
      $('#high_temp_coil .value').html(lowTempValue)
      $('#low_temp_coil .value').html(highTempValue)
    }
  },
  (error) => {
    // TODO: implement better error handling
    console.error("Listener was cancelled due to an error:", error);
  }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 Firebase 实时数据库 Unity 中按字符串和数字中的值对数据库中的子项进行排序 - How do I order children in a database by value in strings and numbers in Firebase Realtime Database Unity 如何使用 Firebase (JS) 在 web 上的实时数据库中的两个日期之间导航? - How to Navigate between two dates in Realtime Database on the web with Firebase (JS)? 如何遍历 Firebase 实时数据库中多个推送键的子项? - How can I iterate through children of multiple push keys in Firebase Realtime Database? Firebase 实时数据库:加载和监控孩子(Swift)——最佳实践? - Firebase realtime database: load & monitor children (Swift) - best practice? 如何在React中更改实时数据库firebase URL - How to change firebase realtime database URL in React 如何从firebase实时数据库中获取数据 - How to retrieve data from firebase realtime database 如何从实时数据库[Firebase]中读取和显示? - How to read and display from realtime database [Firebase]? 如何知道 Firebase 实时数据库上的 updateChildren() 是否成功? - how to know if updateChildren() on Firebase Realtime database was successful or not? 如何反序列化实时 firebase 数据库的这个 hashmap - how to deserialize this hashmap of realtime firebase database 如何在 Firebase 实时数据库中解码这个 json? - How to decode this json in Firebase realtime Database?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM