html response in a iron-ajax request - polymer

My iron-ajax response an object like this:
{
"id": "1",
"idcontenido": "7",
"imagenes": ["carabela.png", "DSC_9565.png"],
"tipo_imagen": "img-circle",
"html": "Esta <b>regi\u00f3n<\/b>"
}
Some ids, an array images... and one 'html' attribute.
This is my element template:
<template>
...
<p>[[ajaxResponse.html]]</p>
<iron-ajax
id="ajax"
url="..."
handle-as="json"
verbose=true
last-response={{ajaxResponse}}
loading="{{cargando}}"> </iron-ajax>
...
</template>
So I want to write the html code from server in my page, but when showing the page, the html code is not being interpretated and I can read literally:
Esta <b>región</b>
How can I fix this interpretated the html code?
Thanks!

Finally I have fix this with an on-response method for the iron-ajax element:
_onResponse: function (e) {
this.$.html.innerHTML = e.detail.response.html;
}
e.detail.response contains an object with a 'html' attribute, the html code I want to write in my page in a 'p' tag with id=html

Related

Reading and displaying json data using Polymer

I am new to polymer and I am trying to read JSON data in a custom-element and display it in other element.
This is my JSON data:
jsonData.json
[
{
"name":"Ladies+Chrome+T-Shirt",
"title":"Ladies Chrome T-Shirt"
},
{
"name":"Ladies+Google+New+York+T-Shirt",
"title":"Ladies Google New York T-Shirt"
}
]
This is my shop-app.html file where I try to read data from JSON file (I am not sure if this is correct or not as I am not able to test it):
<dom-module id="shop-category-data">
<script>
(function(){
class ShopCategoryData extends Polymer.Element {
static get is() { return 'shop-category-data'; }
static get properties() { return {
data: {
type: Object,
computed: '_computeData()',
notify: true
}
}}
_computeData() {
this._getResource( {
url: 'data/jsonData.json',
onLoad(e){
this.set('data.items', JSON.parse(e.target.responseText));
}
})
}
_getResource(rq) {
let xhr = new XMLHttpRequest();
xhr.addEventListener('load', rq.onLoad.bind(this));
xhr.open('GET', rq.url);xhr.send();
}
}
customElements.define(ShopCategoryData.is, ShopCategoryData);
})();
</script>
</dom-module>
This is the element where I want to display the data I read from the JSON file:
<dom-module id="shop-app">
<template>
<app-location route="{{route}}"></app-location>
<app-route
route="{{route}}"
pattern="/:page"
data="{{routeData}}"
tail="{{subroute}}">
</app-route>
<shop-category-data data="{{data}}"></shop-category-data>
<template>
<div> Employee list: </div>
<template is="dom-repeat" items="{{data}}">
<div>First name: <span>{{item.name}}</span></div>
<div>Last name: <span>{{item.title}}</span></div>
</template>
</template>
</template>
<script>
class ShopApp extends Polymer.Element {
static get is() { return 'shop-app'; }
}
customElements.define(ShopApp.is, ShopApp);
</script>
</dom-module>
The line <shop-category-data data="{{data}}"></shop-category-data> should give me the data, which I then try to display using dom-repeat. But nothing is being displayed. So, I think there is some mistake in my reading the JSON data.
Edit:
The JSON is read correctly, it is just not getting reflected back in my:
<shop-category-data data="{{data}}"></shop-category-data>
Computed properties is not returning a value. If you want to define data as a computed property you must return a value from the computed property function _computeData(). But in your case you are using asynchronous XMLHttpRequest. So, if you return a value after calling this._getResource... you need to make it synchronous (which no one recommends).
Plnkr for synchronous method: http://plnkr.co/edit/jdSRMR?p=preview
Another way is calling the method inside ready(). This is asynchronous.
Plnkr: http://plnkr.co/edit/pj4dgl?p=preview
It's not getting reflected back because the json is assigned to data.items, rather than to data itself.
this.set('data', JSON.parse(e.target.responseText));
It's recommended to use <iron-ajax>, and scrap <shop-category-data>. e.g. replace the following line
<shop-category-data data="{{data}}"></shop-category-data>
with
<iron-ajax auto url="data/jsonData.json" handle-as="json"
last-response="{{data}}"></iron-ajax>

how to dynamically append an element to dom-if in Polymer?

My goal is to append an element to existing dom-if dynamically. Problem is that after appending I can see appended element in the DOM three but it never reacts on condition and stays always hidden.
<template>
<template id="domif" is="dom-if" if="[[condition]]" restamp></template>
</template>
ready() {
var el = document.createElement("input");
Polymer.dom(this.$.domif).appendChild(el);
Polymer.dom.flush();
}
Exploring DOM with hardcoded dom-if and input shows that <input /> element is actually not a child of dom-if but lives next to it..
<template>
<template is="dom-if" if="[[condition]]" restamp>
<input />
</template>
</template>
That gave me a clue that I probably should append my element next to dom-if... But now the biggest question is how to say to dom-if that appended element should be rendered if condition is satisfied. Any ideas?
How about adding a span in your dom-if and appending it to that span?
Update after some comments : We need to use this.async for the item to be found. Using the ready-event only works when the condition is true initially. So you could append the element in a conditionChanged-observer - this is a working example :
<dom-module id='my-element1'>
<template>
<template is="dom-if" if="[[condition]]" restamp>
<span id="appendHere"></span>
</template>
</template>
</dom-module>
<script>
Polymer({
is: 'my-element1',
properties: {
condition: {
type: Boolean,
observer: "_conditionChanged"
}
},
_conditionChanged: function(newVal) {
if (newVal) {
this.async(function() {
var el = document.createElement("input");
Polymer.dom(this.$$("#appendHere")).appendChild(el);
Polymer.dom.flush();
});
}
}
});
</script>
Try it here : http://plnkr.co/edit/1IIeM3gSjHIIZ5xpZKa1?p=preview .
A side-effect of using dom-if in this case is that after setting the condition to false, the element disappears completely and gets added on the next condition-change again. So every change before setting the condition to false gets lost. You could work around it by putting the added element somewhere hidden when the condition changes and getting it back later, but I don't think this is a good idea, if the following is an alternative :
The Polymer-team recommends using dom-if only if there is no other way, like hiding the element. So, if it is possible you also could do something like this (condition has to be true to hide the element) :
<dom-module id='my-element1'>
<template>
<span id="appendHere" hidden$="[[condition]]"></span>
</template>
</dom-module>
<script>
Polymer({
is: 'my-element1',
properties: {
condition: Boolean
},
ready: function() {
var el = document.createElement("input");
Polymer.dom(this.$.appendHere).appendChild(el);
Polymer.dom.flush();
}
});
</script>
Try it here :
http://plnkr.co/edit/mCtwqmqtCPaLOUveOqWS?p=preview
The template element itself will not be added to the DOM, this is the reason you can't access it using querySelector or getElementXxx

Unable to Databind localstorage to iron-ajax headers

I'm using the latest Polymer (1.2.0), and I'm having trouble with databinding from iron-localstorage to the iron-ajax headers field. I'm not seeing the Authorization header set when I inspect the request. I've verified the request works when I just create a valid headers object with no databinding.
Am I doing something wrong, or is it not designed to be used like this?
<iron-localstorage name="userToken" value="{{localtoken}}" use-raw></iron-localstorage>
<iron-ajax url="api/twitter/v1/private/gettweets" last-response="{{data}}" auto
headers= '{"Authorization":"Bearer [[localtoken]]}"'
handle-as="json">
</iron-ajax>
<iron-list items="[[data.futuretweets]]" as="item">
<template>
<div>
datetime: <span>[[item.datetime]]</span>
text: <span>[[item.text]]</span>
</div>
</template>
</iron-list>
I think you have a typo error in your compound binding, here is a corrected version:
<iron-ajax url="api/twitter/v1/private/gettweets" last-response="{{data}}" auto
headers= '{"Authorization":"Bearer [[localtoken]]"}'
handle-as="json">
</iron-ajax>
[EDIT] since it is not working, try with a computed function like this:
<iron-ajax url="api/twitter/v1/private/gettweets" last-response="{{data}}" auto
headers='_computeHeaders(localtoken)'
handle-as="json">
</iron-ajax>
where
_computeHeaders(localtoken) {
return {"Authorization": "Bearer " + localtoken};
}
Shouldn't:
_computeHeaders(localtoken) {
return '{"Authorization":"Bearer ' + localtoken + '"}';
}
Instead be:
_computeHeaders: function(localtoken){
return '{"Authorization":"Bearer ' + localtoken + '"}';
}
I've found a little workaround.
I'm using loopback with authentication service enabled and I'm saving the authentication token with iron-localstorage. The problem I've found is that the "auto" of iron-ajax let start the request when any ( almost ) of the iron-ajax parameter change. When the request start the localstorage value hasn't been populated yet
<iron-localstorage name="appdata" value="{{user}}"></iron-localstorage>
and
<iron-ajax auto="{{user.id}}" headers$='{"Authorization" :"{{user.id}}"}' url="/api/data" handle-as="json" last-response="{{data}}"></iron-ajax>
the workaround is inside auto="{{user.id}}". While user isn't loaded the user.id is false. When loaded it become something that match as true. That cause also a change inside the iron-ajax header attribute and cause the "auto" request send to get fired.

Remove child element's attribute from Polymer js

I've a custom element which, among other things, has a core-input and a paper button in it.
When the element is created, the input is disabled, and I want to enable it when I tap the button.
I've tried several ways and can't access the input's attribute.
<paper-input-decorator label="Nombre de usuario" floatingLabel>
<input id="usernameinput" value="{{UserName}}" is="core-input" disabled />
</paper-input-decorator>
<paper-button raised id="edprobutton" on-tap="{{edbutTapped}}">EDITAR</paper-button>
What should I write in
edbutTapped: function () {
},
EDIT
So, I've learned that the problem was that my username input element was inside a repeat template, and that's bad for what I was trying to do. Now I'm trying to bind a single json object to my element, with no luck so far.
What I have right now:
In my Index page:
<profile-page id="profpage" isProfile="true" entity="{{profEntity}}"></profile-page>
<script>
$(document).ready(function () {
var maintemplate = document.querySelector('#fulltemplate');
$.getJSON('api/userProfile.json', function (data) {
var jsonString = JSON.stringify(data);
alert(jsonString);
maintemplate.profEntity = jsonString;
});
}
</script>
In my element's page:
<polymer-element name="profile-page" attributes="isprofile entity">
<template>
<style>
[...]
</style>
<div flex vertical layout>
<core-label class="namepro">{{entity.Name}}</core-label>
<core-label class="subpro">{{entity.CompanyPosition}}</core-label>
<core-label class="subpro">{{entity.OrgUnitName}}</core-label>
</div>
</template>
</polymer-element>
And my JSON looks like this:
{"Name": "Sara Alvarez","CompanyPosition": "Desarrollo","OrgUnitName": "N-Adviser"}
I'm asuming I need to "update" my element somehow after changing its entity attribute?
Try the following
<script>
Polymer({
edbutTapped: function () {
this.$.usernameinput.disabled = false;
}
});
</script>
The this.$ allows you to access controls defined in an elements and the usernameinput is the id you assigned to the input.
This can go below the closing tag of the element you are defining.
'disabled' is conditional-attribute.
So this will be the correct use of it:
<input id="usernameinput" value="{{UserName}}" is="core-input" disabled?="{{isDisabled}}" />
In the prototype:
//first disable the field, can be done in ready callback:
ready: function () {
this.isDisabled = 'true';
}
//set idDisabled to 'false' i.e. enable the input
edbutTapped: function () {
this.isDisabled = 'false';
},
OK this is going to be a long answer (hence why I am not entering this as an edit of my original answer). I've just done something which is functionally the same.
The first thing is this code;
$.getJSON('api/userProfile.json', function (data) {
var jsonString = JSON.stringify(data);
alert(jsonString);
maintemplate.profEntity = jsonString;
});
Polymer has a control called core-ajax - this as it's name suggests makes an ajax call. The other really nice thing is that it can be made to execute when the URL changes. This is the code from the project I've got.
<core-ajax id="ajax"
auto=true
method="POST"
url="/RoutingMapHandler.php?Command=retrieve&Id=all"
response="{{response}}"
handleas="json"
on-core-error="{{handleError}}"
on-core-response="{{handleResponse}}">
</core-ajax>
The auto is the bit which tells it to fire when the URL changes. The description of auto from the polymer documentation is as follows;
With auto set to true, the element performs a request whenever its
url, params or body properties are changed.
you don't need the on-core-response but the on-core-error might be more useful. For my code response contains the JSON returned.
So for your code - it would be something like this
<core-ajax id="ajax"
auto=true
method="POST"
url="/api/userProfile.json"
response="{{jsonString}}"
handleas="json"
on-core-error="{{handleError}}" >
</core-ajax>
Now we have the data coming into your project we need to handle this. This is done by making use of Polymer's data-binding.
Lets detour to the element you are creating. Cannot see anything wrong with the following line.
<polymer-element name="profile-page" attributes="isprofile entity">
We have an element called 'profile-page' with two properties 'isprofile' and 'entity'.
Only because my Javascript leaves a bit to be desired I would pass each property as a seperate entity making that line
<polymer-element name="profile-page" attributes="isprofile name companyposition OrgUnitName">
Then at the bottom of your element define a script tag
<script>
Polymer({
name: "",
companyposition: "",
OrgUnitName: ""
});
</script>
Now back to the calling (profile-page). The following code (from my project) has the following;
<template repeat="{{m in response.data}}">
<map-list-element mapname="{{m.mapName}}" recordid="{{m.Id}}" on-show-settings="{{showSettings}}">
</map-list-element>
</template>
Here we repeat the following each element. In your case you only have one entry and it is stored in jsonString so your template is something like this
<template repeat="{{u in jsonString}}">
<profile-page name="{{u.name}} companyposition="{{u.companyposition}}" OrgUnitName="{{u.OrgUnitName}}">
</profile-page>
</template>
Now we get to the issue you have. Return to your profie-page element. Nothing wrong with the line
on-tap="{{edbutTapped}}"
This calls a function called edbutTapped. Taking the code I gave you earlier
<script>
Polymer({
edbutTapped: function () {
this.$.usernameinput.disabled = false;
}
});
</script>
The only thing to change here is add the following code
created: function() {
this.$.usernameinput.disabled = true;
},
This is inserted after the Polymer({ line. I cannot see in your revised code where the usernameinput is defined but I am assuming you have not posted it and it is defined in the element.
And you should be working, but remember to keep your case consistent and to be honest I've not been - certain parts of Polymer are case sensitive - that catches me out all the time :)

Calling a polymer element within a polyment with JSON as parameter

I am calling a polymer element within another element. The inner polymer element has a published attribute to which I am binding JSON from the parent polymer. However it is not getting reflected.
<polymer-element name="parent-test" attributes="testData">
<template>
This is Parent test
<child-test testdatachild="{{testData}}"></child-test>
</template>
<script>
Polymer('parent-test', {
testData: [],
ready: function () {
debugger;
this.testData = [1, 2, 3, 4]
}
});
</script>
</polymer-element>
<polymer-element name="child-test" attributes="testDataChild">
<template>
<!--{{testDataChild}}-->
<template repeat="{{test in testDataChild}}">
{{test}}
</template>
</template>
<script>
Polymer('child-test', {
testDataChild: [],
ready: function () {
debugger;
}
});
</script>
</polymer-element>
I am not sure what could be the problem here.
Edit:
Seems like I am not having the actual parentContent at the time of generating the child-polymer-element.
If I assign hardcoded values in ready function for this.parentContent, it doesnt work as well.
If I assign hardcoded values in create function for this parent.Content, it works.
So, I am not not sure if this is something related to generating the child polymer element before the values getting binded to parent.
Thanks,
Sam
I modified your plunk example and get it working without your workaround :
Plunk
<polymer-element name="child-test" attributes="testdatachild">
<template>
<br><br>
In Child el.:
<br>
<template repeat="{{test in testdatachild}}">
{{test}}
<br>
</template>
</template>
<script>
Polymer('child-test', {
ready: function () {
}
});
</script>
This is Parent test
<child-test testdatachild="{{testData}}"></child-test>
<br>
</template>
<script>
Polymer('parent-test', {
created: function () {
this.testData = [1, 2, 3, 4];
}
});
</script>
The main problem seems to be the order of the code
I guess it works better to first declare the child, then the parent, as the child is used in the parent...
Also, as specified in the polymer documentation :
polymer
Important: For properties that are objects or arrays, you should always initialize the properties in the created callback. If you set the default value directly on the prototype (or on the publish object), you may run into unexpected “shared state” across different instances of the same element.
Here is modified example of you code that works : Plunk
Why your example is not working, I don't have all answers buy you are right for one:
<!-- This won't work cause:
"Attributes on child-test were data bound prior to Polymer upgrading the element.
This may result in incorrect binding types." -->
This is Parent test
<child-test testdatachild="{{testData}}"></child-test>