从 Polymer 1.0 中的子(或深层子子)元素访问根 BASE API URL
Access root BASE API URL from a child (or deep sub-child) elements in Polymer 1.0
我在我的 Polymer 1.0 环境中创建了许多元素。一些元素是基于我使用 iron-ajax 从我的数据库服务器获得的数据的列表。目前我正在使用我的根应用程序将 API URL 作为元素 属性 传递给需要它的每个元素(或子元素),以便它可以进行调用并显示结果。
虽然这种方法让人感觉有些不对劲。我应该将 AJAX URLs 从根元素传递到需要它的子元素,还是有办法让子元素知道全局设置的 app API URL是吗?
幸运的是我遇到了同样的问题
There is an element for that :)
所以我创建了一个自定义元素来包装我应用程序中的所有 iron-ajax
元素,将其命名为 my-app-api
。
此 my-app-api
元素负责更新嵌套的 iron-ajax
url 属性。
<dom-module id="my-app-api">
<style>
:host {
display: none;
}
</style>
<template>
<content select="iron-ajax"></content>
</template>
</dom-module>
<script>
(function() {
Polymer({
is: 'my-app-api',
properties: {
baseUrl: {
type: String,
value: 'http://localhost:9000'
}
},
attached: function() {
this.updateUrlsAndSign();
},
updateUrlsAndSign: function() {
var ajaxElements = Polymer.dom(this).querySelectorAll('iron-ajax');
var ajaxElementsArray = [].slice.call(ajaxElements);
ajaxElementsArray.forEach(function(ajax) {
var urlAttr = ajax.getAttribute('url');
if ( !urlAttr ) { return; }
ajax.url = this.baseUrl + urlAttr.replace(window.location.origin, '');
ajax.headers = ajax.headers || {};
ajax.headers['Content-Type'] = 'application/json';
...
}.bind(this));
}
});
})();
</script>
用法示例,
<my-app-api>
<iron-ajax
url="/api/videos/"
params="{{requestParams}}"
handle-as="json"
on-response="handleResponse"></iron-ajax>
</my-app-api>
我还没有在 iron-ajax
元素上设置 auto
属性进行测试。
在我的情况下,这不是问题,所以上面的代码对我来说工作得很好。
希望这能帮助您实施更好的解决方案。
我在我的 Polymer 1.0 环境中创建了许多元素。一些元素是基于我使用 iron-ajax 从我的数据库服务器获得的数据的列表。目前我正在使用我的根应用程序将 API URL 作为元素 属性 传递给需要它的每个元素(或子元素),以便它可以进行调用并显示结果。
虽然这种方法让人感觉有些不对劲。我应该将 AJAX URLs 从根元素传递到需要它的子元素,还是有办法让子元素知道全局设置的 app API URL是吗?
幸运的是我遇到了同样的问题
There is an element for that :)
所以我创建了一个自定义元素来包装我应用程序中的所有 iron-ajax
元素,将其命名为 my-app-api
。
此 my-app-api
元素负责更新嵌套的 iron-ajax
url 属性。
<dom-module id="my-app-api">
<style>
:host {
display: none;
}
</style>
<template>
<content select="iron-ajax"></content>
</template>
</dom-module>
<script>
(function() {
Polymer({
is: 'my-app-api',
properties: {
baseUrl: {
type: String,
value: 'http://localhost:9000'
}
},
attached: function() {
this.updateUrlsAndSign();
},
updateUrlsAndSign: function() {
var ajaxElements = Polymer.dom(this).querySelectorAll('iron-ajax');
var ajaxElementsArray = [].slice.call(ajaxElements);
ajaxElementsArray.forEach(function(ajax) {
var urlAttr = ajax.getAttribute('url');
if ( !urlAttr ) { return; }
ajax.url = this.baseUrl + urlAttr.replace(window.location.origin, '');
ajax.headers = ajax.headers || {};
ajax.headers['Content-Type'] = 'application/json';
...
}.bind(this));
}
});
})();
</script>
用法示例,
<my-app-api>
<iron-ajax
url="/api/videos/"
params="{{requestParams}}"
handle-as="json"
on-response="handleResponse"></iron-ajax>
</my-app-api>
我还没有在 iron-ajax
元素上设置 auto
属性进行测试。
在我的情况下,这不是问题,所以上面的代码对我来说工作得很好。
希望这能帮助您实施更好的解决方案。