2015-09-05 33 views
1

我使用Polymer Starter Kit 1.0.3。聚合物入門套件:如何使用後端API?

我的應用程序有不同類型的頁面。其中一些應該將從請求收到的數據呈現給後端API。

但是當應用程序啓動時,所有頁面的所有請求都立即開始。

問題是如何在後端做正確的工作?

回答

0

我和你有同樣的問題,我發現的解決方案是使用我的元素中的方法調用一個函數,當我真正需要它時向後端請求信息。對不起我的英語不好。

+0

我想他是在談論觀察者方法:https://www.polymer-project.org/1.0/docs/devguide/properties.html#change-callbacks –

0

iron-ajax,這是後端主要元素聚合物工作。

這是在我的項目

<iron-ajax auto 
      verbose="true" 
      url="[[apiCategories]]" 
      handle-as="json" 
      on-response="_onCategoriesLoadComplete"></iron-ajax> 
    <iron-ajax auto 
      id="ajaxWeapons" 
      verbose="true" 
      url="[[apiWeapons]]" 
      params="[[apiWeaponsParams]]" 
      debounce-duration="300" 
      handle-as="json" 
      last-response="{{page}}"></iron-ajax> 
    <iron-ajax auto 
      verbose="true" 
      url="{{apiCountries}}" 
      handle-as="json" 
      last-response="{{countries}}"></iron-ajax> 

這是非常有用的,當PARAM變化或ID的變化,整個頁面的數據將刷新,與後臺工作的最簡單的方法的例子。

也許你不想自動請求,例如在我的代碼,當你需要

com._userLogin = function() { 
    var {inputAccount:account,inputPassword:pwd} = this; 
    if (!(account && account.length >= 4)) { 
     this.showToast('Wrong account'); 
     return 
    } 
    if (!(pwd && pwd.length >= 4)) { 
     this.showToast('Wrong password'); 
     return 
    } 

    this.$.ajaxUserLogin.body = {name: account, password: pwd}; 
    this.$.ajaxUserLogin.generateRequest(); 
    }; 

    com._onUserLoginComplete = function (e, ajax) { 
    if (ajax.response.error) { 
     this.showToast('Login faield:' + ajax.response.error); 
     return 
    } 
    this.user = ajax.response; 
    }; 

總之

<iron-ajax id="ajaxUserRegister" 
      verbose="true" 
      url="{{apiUsers}}" 
      method="PUT" 
      on-response="_onUserRegisterComplete" 
      content-type="application/json" 
      handle-as="json"></iron-ajax> 
<iron-ajax id="ajaxUserLogin" 
      verbose="true" 
      url="{{apiUsers}}" 
      method="POST" 
      on-response="_onUserLoginComplete" 
      content-type="application/json" 
      handle-as="json"></iron-ajax> 
<iron-ajax id="ajaxUserGet" 
      verbose="true" 
      url="{{apiUsers}}" 
      method="GET" 
      headers="[[user.headers]]" 
      on-response="_onUserGetComplete" 
      content-type="application/json" 
      handle-as="json"></iron-ajax> 

您還可以使用後端的來源,定義你的後端資源作爲iron-ajax,這是聚合物如何與後端工作。

相關問題