如何在聚合物中加载组件后运行AJAX

时间:2018-02-12 14:08:40

标签: ajax lifecycle polymer-2.x

我试图在父组件中自动运行此AJAX调用,但收到Uncaught TypeError: Cannot read property 'ajax' of undefined错误。我查看了Polymer生命周期方法,但在调用之前,它们似乎都没有确保加载AJAX元素。

<template>
  <iron-ajax id="ajax"
    url="https://api/endpoint"
    method="post"
    handle-as="json"
    content-type="application/json"
    body="[[request]]"
    last-response="{{response}}"></iron-ajax>
 </template>

定义属性:apiKey,用户名等

connectedCallback() {
  this.setCredentials();
}

setCredentials() {
  this.set('username', sessionStorage.getItem('username'));
  this.set('apiKey', sessionStorage.getItem('apiKey'));
  this.getResponse();
}

getResponse() {
  if (this.username && this.apiKey && this.$.ajax != undefined) {
    this.request = {
      "username": this.username,
      "apiKey": this.apiKey,
      "text": "some text"
    };
    let request = this.$.ajax.generateRequest();
    request.completes.then(req => {
      // do something
    })
  } else {
    this.getResponse();
  }
}

如何确保整个文档准备好进行AJAX调用?

2 个答案:

答案 0 :(得分:0)

以下方式可以更有效地确保整个文档准备就绪:

static get observers() {
  return [  'checkUsernameAndApiKey(username, apiKey)' ];
}

ready() {
  super.ready();
     setTimeout(()=>{
           // In order to wait this property loaded async with another ways
           this.set('username', sessionStorage.getItem('username'));
           this.set('apiKey', sessionStorage.getItem('apiKey'));
     }, 900)

}

checkUsernameAndApiKey(u, a) {
  // if failed to get sessionStorage, u or a will be undefined.
  if (u && a) {
    this.set('request', {"username": this.username, "apiKey": this.apiKey, "text": "some text"};
    this.$.ajax.generateRequest();
    ...
  }
}

Limit the Number of Entries Scanned

答案 1 :(得分:0)

当我想要使用我的元素加载XHR请求时,我使用ready()方法:

<template>
  <iron-ajax id="ajax"
    url="https://api/endpoint"
    method="post"
    handle-as="json"
    content-type="application/json"
    body="[[request]]"
    on-response="_checkUsernameAndApiKey"
    on-error="_handleError">
  </iron-ajax>
</template>

...

ready() {
  super.ready();
  this.$.ajax.generateRequest();
}

_checkUsernameAndApiKey(e) {
  if (e.detail.response) {
    let response = e.detail.response;
    ...
  } else {
    console.log(e.detail);
  }
}

_handleError(e) {
  console.log(e.detail.error);
}