我在使用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。
这是计算的绑定代码:
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,但似乎没有返回绑定在纸卡的image属性中的正确值。
有任何想法吗?先感谢您 :)
我尝试将其更改为
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>
如您所见,我在计算的绑定函数中添加了索引参数,并为与索引串联在一起的纸卡指定了一个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引用图像属性。
谢谢你们的帮助。 @zerohero