我编写了以下自定义元素:
<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/