我是聚合物新手,我正在尝试创建一个接受请求并发回响应的自定义服务。但是,即使我可以看到在服务页面中设置了该对象,我也面临着访问响应对象的问题。
请查看服务代码:x-custom.html
<link rel="import" href="bower_components/polymer/polymer.html">
<link rel="import" href="bower_components/iron-ajax/iron-ajax.html">
<dom-module id="x-custom">
<style>
</style>
<template>
<iron-ajax
id="ajax"
url=""
handle-as="json"
on-response="hresponse"
debounce-duration="300">
</iron-ajax>
</template>
<script>
Polymer({
is: 'x-custom',
properties: {
user: String,
responseData:{
type:Object,
notify:true
}
},
attached: function() {
this.$.ajax.url = "http://myapitesing/api/users/"+this.user;
this.$.ajax.generateRequest();
},
hresponse: function(request) {
// Make a copy of the loaded data
respObj = request.detail.response;
if(respObj){
//console.log(respObj);
this.responseData = respObj;
alert(respObj.email);
}
}
});
</script>
</dom-module>
现在查看访问服务的元素:user-details.html
<link rel="import" href="bower_components/polymer/polymer.html">
<link rel="import" href="x-custom.html">
<dom-module id="user-details">
<style>
</style>
<template>
<x-custom user="6f299d3cb8214c079433d7bb98a4a5ed" responseData={{responseData}} ></x-custom>
<h1>{{responseData.email}}</h1>
</template>
<script>
Polymer({
is: 'user-details'
});
</script>
</dom-module>
现在我通过以下方式调用我的 idex.html 中的 user-details 元素
<user-details></user-details>
它成功获取了详细信息,但是,{{responseData.email}} 并未在 user-details.html 页面中显示电子邮件字符串。
如果我尝试在 x-custom.html 页面中获取相同的值,我可以看到 responseData.email 值。 (请参阅 x-custom.html 内 hresponse 函数中的警报)
请帮助我,如果我遗漏了什么地方,请告诉我。
最佳答案
注意我还没有采用你的两个元素并对此进行测试,但我的猜测是你的问题出在你的 <user-details>
上。您所在的行:
<x-custom user="6f299d3cb8214c079433d7bb98a4a5ed" responseData={{responseData}} ></x-custom>
除非这是一个拼写错误,否则它绝对不会绑定(bind)到 responseData
因为你的属性是驼峰命名法。你需要做的是:
<x-custom user="6f299d3cb8214c079433d7bb98a4a5ed" response-data={{responseData}} ></x-custom>
您可能还需要创建 responseData
在<x-custom>
具有 notify: true
的属性;我总是忘记。
关于javascript - Polymer 1.0 数据绑定(bind)和访问ajax响应对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31501464/