简体   繁体   中英

Store returned values from the iron-ajax request in variables (Polymer)

I am working the first time with Polymers iron-ajax element and came across a problem which I believe is fairly simple to solve but I am unable to find a solution online.

I retrieve user details with the iron-ajax element and loop through it with the dom-repeat. The first and last name of a user are getting placed in a custom card element that I created to display users. Everything works fine except that I am unable to store the returned id value in a variable. I am sure this is possible with the usage of data binding but I couldn't get it to work. And even when I try to get the value with getAttribute in my JavaScript it just returns null.

In the code below my iron-ajax request & response can be found including my awkward attempt to get the id value {{item.id}}.To do so I created a on-tap function when a user clicks on one of the cards which then should get the value of the stdId attribute.

<dom-module id="my-students-view">
<template>

  <style>
    :host {
      display: block;
    }
  </style>

  <!-- Iron-Ajax created connection and gets data -->
  <iron-ajax
    auto
    id="requestRepos"
    url="http://api.dev/user/"
    handle-as="json"
    loading="{{isloading}}"
    last-response="{{response}}"></iron-ajax>

  <!-- dom-repeat iterates the response -->
  <template is="dom-repeat" items="[[response.data]]" sort="sortData">
    <student-card
      id="studentCard"
      to="http://localhost:8080/profile-view/{{item.id}}"
      picsrc="../../images/anonymous.jpg"
      name="{{item.first_name}} {{item.last_name}}"
      stdId="{{item.id}}"
      on-tap="sendId"></student-card>

  </template>
</template>

<script>
Polymer({
  is: 'my-students-view',

  properties: {
    stdId: {
      notify: true,
    }
  },

  //Sort the array/data alphabetically
  sortData: function(a, b) {
    if(a.first_name < b.first_name) return -1;
    if(a.first_name > b.first_name) return 1;
    return 0;
  },

  //Try to get the id value of a the student card 
  sendId: function() {
    var idPropertie = this.$$("#studentCard");
    var idValue = idPropertie.getAttribute('stdId');
    console.log('the id is:' + idValue);
  },

});

</script>
</dom-module>

Rewrite the sendId function:

sendId: function(event) {
  var idValue = event.model.item.id;
  console.log('the id is:' + idValue);
},

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM