javascript - Polymer - 定期刷新 API 调用的数据

标签 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">{{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>

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

最佳答案

您可以使用 native setTimeout : setTimeout(() => this.someMethod(), 500);

此外,<iron-ajax>将允许您轻松发出ajax请求(docs)。

结果示例:

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

<dom-module id="my-voltage">
  <template>
        <iron-ajax id="ajax"
                   auto
                   url="api/call"
                   last-response="{{data}}"
                   on-response="_onResponse"
                   handle-as="json">
        </iron-ajax>
        <div class="circle">[[data.value]]</div>
        <div class="circle">[[data.timestamp]]</div>
    </template>
  <script>
    class MyVoltage extends Polymer.Element {
      static get is() {
        return "my-voltage";
      }

      static get properties() {
        return {
          data: Object
        };
      }

      _onResponse() {
        setTimeout(() => this.$.ajax.generateRequest(), 5000);
      }
    }
    customElements.define(MyVoltage.is, MyVoltage);
  </script>
</dom-module>

在这里,_onResponse()每次响应后都会被调用,并会在 5 秒(5000 毫秒)延迟后创建一个新请求。

关于javascript - Polymer - 定期刷新 API 调用的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45109116/

相关文章:

javascript - Paper 工具栏 javascript 没有反应

javascript - Bootstrap Javascript 无法在 Firefox 和 Safari IOS 中运行

javascript - Three.js - 它有顶点索引着色吗?

java - 股票行情有问题

javascript - 基于 REST 的 polymer 应用程序

javascript - 如何在 Polymer 上创建自定义元素的实例

javascript - 函数属性不是 Polymer 中的函数

javascript - 隐藏表格第一行的删除图标 - ReactJS

javascript - 从 Mozilla 插件在终端/命令提示符中执行系统命令

javascript - 以跨浏览器的方式找到视口(viewport)的确切高度和宽度(无原型(prototype)/jQuery)