Как вызвать iron-ajax при нажатии кнопки в Polymer-3.x? - PullRequest
0 голосов
/ 28 августа 2018

Я создаю полимерный элемент, в котором используется железо-аякс. Это приведет к открытому API для извлечения случайного лиса imageUrl и отображения в DOM.

Требование

При нажатии button я хочу сделать новый вызов API, это даст мне новый URL. В настоящее время я использую <button type="button" onClick="window.location.reload();">. но это обновляет страницу.

Задача

Я прошел через это решение StackOverflow и изменил его на решение версии 3.

class MyFox extends PolymerElement {
  static get template() {
    return html`
      <dom-bind>
      <template id="temp"> 
          <iron-ajax
            auto
            id="dataAjax"
            url=""
            handle-as="json"
            on-response="handleResponse"
            id="apricot">
          </iron-ajax>

          <button type="button" onClick="window.location.reload();">Next Image</button>
          <br> <br>
          <img src="[[imgUrl]]" width="300">
      </template>
      </dom-bind>
    `;
  }
  static get properties() {
    return {
      prop1: {
        type: String,
        value: 'my-fox',
      },
      imgUrl: {
        type: String,
      }
    };
  }
  handleResponse(event, res) {
    this.imgUrl = res.response.image; 
  }
  nextImg() {
    // new call to iron-ajax for new image
    var temp = document.querySelector('#temp');
    temp.$.dataAjax.generateRequest();
  }
}

window.customElements.define('my-fox', MyFox);

Но я получаю следующую ошибку. метод слушателя handleResponse не определено

fox error

Вопрос

Как вручную вызвать iron-ajax при нажатии кнопки, чтобы я мог получить новый response or imageUrl и страница не обновилась?

1 Ответ

0 голосов
/ 28 августа 2018

В вашем веб-компоненте есть пара ошибок

class MyFox extends PolymerElement {
  static get template() {
    return html`
          <iron-ajax
            auto
            id="dataAjax"
            url=""
            handle-as="json"
            on-response="handleResponse">
          </iron-ajax>

          <button type="button" on-tap="nextImg">Next Image</button>
          <br> <br>
          <img src="[[imgUrl]]" width="300">
    `;
  }
  static get properties() {
    return {
      prop1: {
        type: String,
        value: 'my-fox',
      },
      imgUrl: {
        type: String,
      }
    };
  }
  handleResponse(event, res) {
    this.imgUrl = res.response.image; 
  }
  nextImg() {
    // new call to iron-ajax for new image
    this.$.dataAjax.generateRequest();
  }
}

window.customElements.define('my-fox', MyFox);
...