Search code examples
ajaxpolymerpolymer-1.0polymer-elements

RestApi call through iron-ajax of polymer


I am developing a polymer app and I want to make a call to the RestApi. this is the how the request body is

{
    "languageId": Presently English is the only supported language. Always 1, 
    "productCode":"Medicus",
    "timeZoneName":"Time zone name of device. For e.g. Asia/Calcutta",
    "timeZoneOffset": Time zone offset from UTC in milliseconds. For e.g. IST = 19800000,
    "user":{
     "firstName":"First name of the user",
     "lastName":"Last name of the user",
     "middleName":"Middle name of the user",
     "password":"Password provided by the user",
     "userTypeId":2 = Doctor, 3 = User,
     "fields":[
         {
            "Id":1,
            "values":["Mobile number provided by the user”]
         }
     ]
    }
}

i am not getting the proper idea of how i should specify these parameters in the params='{}' of iron-ajax element.


Solution

  • Put something like this in your template (I am assuming POST to your rest API, since you said body in your question. If its GET replace body= with params=

    <iron-ajax
           id="fetchday"
           url="/api/fetchday"
           handle-as="json"
           content-type="application/json"
           method="POST"
           body="[[params]]"
           last-response="{{results}}"
           on-response="_gotData"
           on-error="_error"></iron-ajax>
    

    And in your polymer element properties

    Polymer({
      is: 'my-element'
      properties: {
        params: {
         type: Object
        } 
      },
      _someFunction: function() {
        this.params = //ASSIGN YOUR JSON OBJECT TO PARAMS HERE
        this.$.fetchday.generateRequest();
      },
      _gotData: function(e) {
        //response data is in both this.results and e.detail.response
     },
     _error: function() {
     }
    });