Search code examples
node.jsajaxpolymer

Loop ajax request within a polymer element


quick question, i'm almost there. I have an express server that send a random string (for testing purpose) each time I make a GET on /value :

.get('/value', function(req, res){
    
    res.send(un());
})

And I have a Polymer element that make ajax request through (v1.4.4) it works really well when I do the call once, but I dont understand how to make the call automatically.

Here is the element :

<!DOCTYPE html>
<link rel="import" href="./../bower_components/polymer/polymer.html">
<link rel="import" href="./../bower_components/iron-ajax/iron-ajax.html">
<dom-module id="neito-photoresistor">
    <template>
        <style>
        </style> 
        
        <span>Ambient luminosity = <span>{{lum_pct}}</span> %</span>
        <iron-ajax id="ajaxValueUpdater" url="http://localhost:3000/value" on-response="_updateValue" handle-as="text" debounce-duration="500">
        </iron-ajax>
    </template>
    <script>
        Polymer({
            is: 'neito-photoresistor',
            properties: {
                lum_pct: {
                    type: String,
                    value: 'uniqid waiting to change...',
                    reflectToAttribute: true
                }
            },
            ready: function() {
                this.$.ajaxValueUpdater.generateRequest();//Launch the request once and it is working
            },
            _updateValue: function(event){
                this.lum_pct = event.detail.response;//It work
            }
        });
    </script>
</dom-module>

So I tried with setInterval(), with async() and with while(true)(really a bad idea)

Here are my tries and the error given :

ready: function() {
                this.async(this.$.ajaxValueUpdater.generateRequest(), 2000);
            },

Error : Uncaught TypeError: callback.call is not a function at polymer.html:1315

Other try :

ready: function() {
                setInterval(this.$.ajaxValueUpdater.generateRequest(), 2000);
            },

Error : VM93:1 Uncaught SyntaxError: Unexpected identifier

And the last one, I was sure it was going to work :

ready: function() {
                var ajax = this.$.ajaxValueUpdater;
                setInterval(function(ajax){
                    ajax.generateRequest();
                }, 2000);
                
            },

Error : Uncaught TypeError: Cannot read property 'generateRequest' of undefined at neito-photoresistor.html:26 (Same error if replace the last example with this.async)

I know I'm at one line of the solution. Could someone help me ?


Solution

  • Change your ready function as follow:

    ready: function() {
                var ajax = this.$.ajaxValueUpdater;
                setInterval(() => {
                    ajax.generateRequest();
                }, 2000);
    
            },