我在使用 Polymer 中的 dom-repeat 显示图像时遇到问题。我使用 Firebase Storage 来存储图像。
<firebase-query id="productsQuery"
data="{{products}}"
limit-to-first="2"></firebase-query>
上述元素的路径是动态更新的并且工作正常。
<template is="dom-repeat" items="[[products]]" index-as="index">
<paper-card image="[[computePhotoURL(item.$key)]]" heading="[[item.name]]">
<div class="card-content">
<p class="shop-name">[[shopName]]</p>
<small>Php [[item.price]]</small>
</div>
</paper-card>
</template>
从上面的元素来看,一切工作正常,它们显示信息,但使用计算函数,它不会正确返回 url。
这是计算的绑定(bind)代码:
computePhotoURL: function(key) {
var photo;
firebase.storage()
.ref('users/' + this.data[0].$key + '/products/' + key)
.getDownloadURL()
.then( function(url) {
photo = url;
return url;
}.bind(this)).catch( function(error) {
console.log('there was an error');
});
return photo;
}
通过记录上述函数中的 url,它会显示来自 firebase 存储的正确 url,但它似乎没有返回纸卡图像属性中绑定(bind)的正确值。
有什么想法吗?预先感谢您:)
我尝试将其更改为
computePhotoURL: function(key) {
var photo;
firebase.storage()
.ref('users/' + this.data[0].$key + '/products/' + key)
.getDownloadURL()
.then( function(url) {
photo = url;
console.log(photo);
//logs correct url
}.bind(this)).catch( function(error) {
console.log('there was an error');
});
console.log('photo', photo);
//logs undefined
return photo;
}
它会在正确的 url 之前先记录未定义的内容。所以照片变量在改变之前就被返回了。帮忙看看如何解决这个问题? JS 不太好:(
最佳答案
抱歉,我刚刚记得发布答案:
<template is="dom-repeat" items="[[products]]" index-as="index">
<paper-card id="card[[index]]" image="[[computePhotoURL(item.$key, index)]]" heading="[[item.name]]">
<div class="card-content">
<p class="shop-name">[[shopName]]</p>
<small>Php [[item.price]]</small>
</div>
</paper-card>
</template>
正如您所看到的,我在计算绑定(bind)函数中添加了一个索引参数,并为与索引连接的纸卡指定了一个 ID,以区分其他卡。
computePhotoURL: function(key, index) {
var id = '#card' + index;
firebase.storage()
.ref('users/' + this.data[0].$key + '/products/' + key)
.getDownloadURL()
.then( function(url) {
this.$$(id).image = url;
}.bind(this)).catch( function(error) {
console.log('there was an error', error);
});
}
因此,每当获取图像 url 时,它都会使用 this.$$(query) :) 引用基于 dom-repeater 生成的 id 的图像属性:)
感谢大家的帮助,特别是。 @零英雄
关于javascript - 通过计算绑定(bind)在 Polymer 中使用 dom-repeat 从 Firebase 动态获取文件 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39532309/