Polymer 1.0 iron-ajax call is made but on-response does not fire and the data isn't bound

こ雲淡風輕ζ 提交于 2019-12-24 03:59:09

问题


I have the following code

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


<dom-module id="custom-Element">
    <iron-ajax auto
               url="http://api.openweathermap.org/data/2.5/forecast"
               params='{"q":"California"}'
               handle-as="json"
               on-response="handleResponse"
               last-response="{{ajaxResponse}}"></iron-ajax>
    <span>{{ajaxResponse.city.name}}</span>
    <script>
        Polymer({
            is: 'custom-Element',
            handleResponse: function ()
            {
                console.log('  blalba');
            },
            ready: function () {
                setInterval(function () { console.log(this.ajaxResponse); }, 1000);

            }
        });
    </script>
</dom-module>

My problem is even though the ajax call is happening and data is retrieved the on-response "handleResponse" method is never being fired and the "ajaxResponse" isn't being populated either. I tried looking at different tutorials and code demos but I can't seem to find what's wrong with my code.


回答1:


When using a <dom-module The iron-ajax or anything else needs to go inside a <template as its placed in the shadow dom.

eg

<dom-module id="custom-Element">
    <template>
    <iron-ajax auto ..... >
    <span>{{ajaxResponse.city.name}}</span>
    </template>
..
...
.....
</dom-module>

Ill explain a bit further.

Because you are creating a dom-module custom-Element and you are calling it with <custom-Element></custom-element> to display the data anything inside dom-module needs to be inside a <template></template> so its placed in the shadow dom and registers the id name custom-Element.

Think of the html5 <video> tag

Now by doing

<video width="320" height="240" controls>
  <source src="movie.mp4" type="video/mp4">
</video>

it will play a video.

However when you inspect <video> you cant see any special css like for the play /stop pause buttons or any javascript because its placed in the Shadow Dom of the browser and its hidden away.

So the video tag its just a name build in the browser so you can use to play videos. To put that in the shadow dom you need a <template>

With polymer you do the same

<dom-module id="any-name">

<template>
...
</template>

</dom-module>

and to use it

<any-name></any-name>

same like the <video></video> tag in html5.

Good article here to read about web components and why templates are used



来源:https://stackoverflow.com/questions/31499476/polymer-1-0-iron-ajax-call-is-made-but-on-response-does-not-fire-and-the-data-is

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!