Javascript 聚合-从API调用定期刷新数据

Javascript 聚合-从API调用定期刷新数据,javascript,polymer,Javascript,Polymer,我编写了以下自定义元素: <link rel="import" href="../bower_components/polymer/polymer-element.html"> <link rel="import" href="shared-styles.html"> <dom-module id="my-voltage"> <template is="auto-binding"> <div class="circle">

我编写了以下自定义元素:

<link rel="import" href="../bower_components/polymer/polymer-element.html">
<link rel="import" href="shared-styles.html">

<dom-module id="my-voltage">
  <template is="auto-binding">
    <div class="circle">{{volts}}</div>
    <div class="circle">{{time}}</div>
  </template>
  <script>
  function httpGet(theUrl)
  {
      var xmlHttp = new XMLHttpRequest();
      xmlHttp.open( "GET", theUrl, false ); 
      xmlHttp.send( null );
      return xmlHttp.responseText;
  }

    class MyVoltage extends Polymer.Element {
      static get is() {
        return "my-voltage";
      }    
      static get properties() {
        return {
          volts: {
            type: String,
            notify: true,
            reflectToAttribute: true

          },
        }
      }    
      constructor() {
        super();
          var volt = JSON.parse(httpGet('API_call'));
          var voltage = volt.value.toString();
          var ts = volt.timestamp.toString();
          this.volts = voltage;
          this.time = ts;
        }

    }
    customElements.define(MyVoltage.is, MyVoltage);  

  </script>
</dom-module>

{{volts}}
{{time}}
函数httpGet(theUrl)
{
var xmlHttp=new XMLHttpRequest();
open(“GET”,theUrl,false);
xmlHttp.send(空);
返回xmlHttp.responseText;
}
MyVoltage类聚合物元件{
静态get是(){
返回“我的电压”;
}    
静态获取属性(){
返回{
伏特:{
类型:字符串,
通知:正确,
reflectToAttribute:真
},
}
}    
构造函数(){
超级();
var volt=JSON.parse(httpGet('API_call');
无功电压=电压值toString();
var ts=volt.timestamp.toString();
这是1.5伏=电压;
this.time=ts;
}
}
自定义元素。定义(MyVoltage.is,MyVoltage);

这将通过API调用获取数据,并在加载时显示数据。但是,我需要它定期刷新数据,而用户不必重新加载整个页面。我一直在阅读文档,但找不到解决方案。我到底需要把代码放在哪里来定期调用API并获取新数据?我怎样才能做到这一点

Hi-XMLHttpRequest已被弃用。您可以使用新的或Google提供的iron ajax。

您可以使用本机的
setTimeout
setTimeout(()=>this.someMethod(),500)

另外,
将允许您轻松地发出ajax请求()

示例结果:


[[data.value]]
[[data.timestamp]]
MyVoltage类聚合物元件{
静态get是(){
返回“我的电压”;
}
静态获取属性(){
返回{
数据:对象
};
}
_onResponse(){
setTimeout(()=>this.$.ajax.generateRequest(),5000);
}
}
自定义元素。定义(MyVoltage.is,MyVoltage);

这看起来应该可以工作,但不行,我仍在努力找出问题所在。(我确实用实际的api调用替换了api/调用)我更改了代码并添加了
数据作为属性,你能检查一下是否解决了它吗?我想唯一的问题是Handles而不是handle数据,我忘记了导入,否则就太完美了,谢谢!:)抢手货更新了答案。不客气。