我有一个组件,它使用 的实例<iron-ajax>
从后端检索数据,我想用它<iron-request>
来发送更新,例如 POST/DELETE 请求。
一切都在第一次完美运行。但是,如果再次调用请求,我会收到错误消息:
未捕获的类型错误:无法读取未定义的属性“then”
我的模板定义如下所示:
...
<iron-ajax id="ajax" auto verbose
url="/cart-api/"
last-response="{{ajaxResponse}}"
handle-as="json">
</iron-ajax>
<iron-request id="xhr"></iron-request>
...
在我的组件脚本中,我使用发送 POST的send()
方法:<iron-request>
var me = this;
this.$.xhr.send({
url: "/cart-api",
method: "POST",
body: JSON.stringify(entry)
}).then(function() {
me._refresh();
}, function() {
console.error("POST failed");
});
错误消息表明send
已返回undefined
而不是有效的 Promise 对象。
所以我的问题是:一个<iron-request>
元素实际上是可重用的吗?我需要做任何事情来刷新或重新初始化它吗?
更新
感谢@Zikes,我更新了我的代码如下:
<iron-ajax id="ajaxGet" auto
url="/cart-api/"
last-response="{{ajaxResponse}}"
handle-as="json">
</iron-ajax>
<iron-ajax id="ajaxPost" url="/cart-api" method="POST" on-response="_refresh"></iron-ajax>
<iron-ajax id="ajaxDelete" method="DELETE" on-response="_refresh"></iron-ajax>
insertEntry: function(entry) {
this.$.ajaxPost.body = JSON.stringify(entry);
this.$.ajaxPost.generateRequest();
},
_handleRemove: function(e) {
var entry = e.currentTarget.entry;
this.$.ajaxDelete.url = "/cart-api/" + entry.id;
this.$.ajaxDelete.generateRequest();
},
_refresh: function() {
this.$.ajaxGet.generateRequest();
},