I'm using polymer starter kit.I have to make many API calls in different HTML pages and for each API call, I'm using "iron-ajax" in that for 'url' property I'm assigning REST API URL.
URL will be like "https://XXXXX.in/YY/YY/YY" ,Here base URL XXXXX is same for all API call and YY will change.So how can I store Base URL XXX in one configuration file and access that value in all the pages for all "iron-ajax"? where I should access Base URL, is it inside polymer's 'ready' function for all the pages?
OPTION 1
In Polymer you would store values as properties. If you have the base URL as a property on top of the node tree (in the first parent element), you can pass it on to any child element (and then they can pass it further down).
Your top element:
<link rel="import" href="./child-el.html">
<dom-module id="main-el">
<template>
<child-el base-url="[[baseUrl]]"></child-el>
</template>
</dom-module>
<script>
Polymer({
is: 'main-el',
properties: {
baseUrl: {
type: String,
value: 'https://XXXXX.in'
}
}
});
</script>
The child:
<dom-module id="child-el">
<template>
<iron-ajax url="[[baseUrl]]/YY/YY/YY"></iron-ajax>
</template>
</dom-module>
<script>
Polymer({
is: 'child-el',
properties: {
baseUrl: {
type: String
}
}
});
</script>
OPTION 2
You can put all ajax calls in one element that doesn't render anything on the screen and include that element anywhere you need.
<link rel="import" href="./api-handler.html">
<dom-module id="main-el">
<template>
<api-handler id="api-handler"></api-handler>
</template>
</dom-module>
<script>
Polymer({
is: 'main-el',
attached () {
this.$['api-handler'].makeRequest();
}
});
</script>
OPTION 3
Store the baseUrl property in a Polymer behavior and include that in your elements.
OPTION 4
You can attach the value to the globally accessible window object. Your config.html would look like:
<script>
(function (Config) {
Config.BASE_URL = 'https://XXXXX.in';
})(window.Config = window.Config || {});
</script>
Then you import that in your index.html:
<link rel="import" href="./config.html">
..and Config.BASE_URL will be available in all your elements.