我有一个使用 <iron-ajax>
实例的组件从后端检索数据,我想使用 <iron-request>
发送更新,例如 POST/DELETE 请求。
第一次一切都完美无缺。但是,如果再次调用请求,则会出现错误:
Uncaught TypeError: Cannot read property 'then' of undefined
我的模板定义如下所示:
...
<iron-ajax id="ajax" auto verbose
url="/cart-api/"
last-response="{{ajaxResponse}}"
handle-as="json">
</iron-ajax>
<iron-request id="xhr"></iron-request>
...
在我的组件脚本中,我使用了 send()
<iron-request>
的方法|发送 POST:
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();
},
最佳答案
<iron-ajax>
组件生成一个新的 <iron-request>
对于每个新请求:https://github.com/PolymerElements/iron-ajax/blob/master/iron-ajax.html#L442
如果您正在寻找可重用性(以及其他不错的功能,如去抖动),您最好使用 <iron-ajax>
组件。
关于javascript - polymer 1.0 : Multiple calls to send() method of iron-request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30603280/